Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 374
Narek Avatar asked Oct 04 '11 12:10

Narek


1 Answers

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.

like image 176
Kerrek SB Avatar answered Oct 09 '22 03:10

Kerrek SB