How to check if the template parameter of the function has a certain type?

Narek picture Narek · Oct 4, 2011 · Viewed 12.8k times · Source

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
    ...........
    //check if T == B do some other thing
}

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

Answer

Kerrek SB picture Kerrek SB · Oct 4, 2011

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.