In my template-ized function, I'm trying to check the type T is of a specific type. How would I do that?
p/s I knew the template specification way but I don't want to do that.
template<class T> int foo(T a) {
// check if T of type, say, String?
}
Thanks!
I suppose you could use the
std::type_info
returned by the typeid operatorInstead of checking for the type use specializations. Otherwise, don't use templates.
You can perform static checks on the type that you have received (look at the boost type traits library), but unless you use specialization (or overloads, as @litb correctly points out) at one point or another, you will not be able to provide different specific implementations depending on the argument type.
Unless you have a particular reason (which you could add to the question) not to use the specialization in the interface just do specialize.
If you are using C++11 or later, std::is_same does exactly what you want:
http://en.cppreference.com/w/cpp/types/is_same
You can check using
type_traits
(available in Boost and TR1) (e.g.is_same
oris_convertible
) if you really want to avoid specialization.If you don't care about compile-time, you may use boost::is_same.
As of C++11, this is now part of the standard library