How to check if the template parameter of the function has a certain type?
Say I have a function with template type T and two other classes A and B.
template <typename T>
void func(const T & t)
{
...........
//check if T == A do something
....开发者_如何学C.......
//check if T == B do some other thing
}
How can I do these two checks (without using Boost library)?
If you literally just want a boolean to test whether T == A
, then you can use is_same
, available in C++11 as std::is_same
, or prior to that in TR1 as std::tr1::is_same
:
const bool T_is_A = std::is_same<T, A>::value;
You can trivially write this little class yourself:
template <typename, typename> struct is_same { static const bool value = false;};
template <typename T> struct is_same<T,T> { static const bool value = true;};
Often though you may find it more convenient to pack your branching code into separate classes or functions which you specialize for A
and B
, as that will give you a compile-time conditional. By contrast, checking if (T_is_A)
can only be done at runtime.
Create function templates with specializations, that will do the thing you want.
template <class T>
void doSomething() {}
template <>
void doSomething<A>() { /* actual code */ }
template <class T>
void doSomeOtherThing() {}
template <>
void doSomeOtherThing<B>() { /* actual code */ }
template <typename T>
void func(const T & t)
{
...........
//check if T == A do something
doSomething<T>();
...........
//check if T == B do some other thing
doSomeOtherThing<T>();
}
If you want to have a special implementation of func
for some parameter type, simply create an overload specific for that type:
template <typename T>
void func(const T & t) {
// generic code
}
void func(const A & t) {
// code for A
}
精彩评论