How to check if a template parameter has a specific type?

Say I have a function with pattern type T and two other classes A and B.

template <typename T> void func(const T & t) { ........... //check if T == A do something ........... //check if T == B do some other thing } 

How can I perform these two checks (without using the Boost library)?

+7
source share
3 answers

If you literally just want the boolean to be checked: T == A , you can use is_same , available in C ++ 11 as std::is_same , or before that in TR1 as std::tr1::is_same :

 const bool T_is_A = std::is_same<T, A>::value; 

You can simply write this small 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, although it may be more convenient for you to package your fork code into separate classes or functions that you specialize in A and B , as this will give you a compile-time condition. In contrast, an if (T_is_A) check is only possible at run time.

+8
source

Create function templates with specializations that will do what you need.

 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>(); } 
+7
source

If you want to have a special implementation of func for some type of parameter, just create an overload for this type:

 template <typename T> void func(const T & t) { // generic code } void func(const A & t) { // code for A } 
+3
source

All Articles