how to do an if else depending type of type in c++ template? [duplicate]
You could use typeid
:
if (typeid(T) == typeid(int))
Or you could use the std::is_same
type trait:
if (std::is_same<T, int>::value)
What you want is probably something like a compile-time if. Unfortunately, C++11 has no native support for such a language construct.
However, if you just want to check whether two types are identical, the std::is_same<>
type trait should help you:
#include <type_traits> // <== INCLUDE THIS STANDARD HEADER
// class template:
template <class T>
class mycontainer
{
T element;
public:
mycontainer (T arg) {element=arg;}
T increase ()
{
if (std::is_same<T, int>::value) // <== THIS IS HOW YOU WOULD USE IT
return ++element;
if (std::is_same<T, char>::value) // <== THIS IS HOW YOU WOULD USE IT
{
if ((element>='a') && (element<='z'))
element+='A'-'a';
}
return element;
}
};
However, keep in mind that the condition is evaluated at run-time, even though the value of is_same<T, int>::value
is known at compile-time. This means that both the true
and the false
branch of the if
statement must compile!
For instance, the following would not be legal:
if (std::is_same<T, int>::value)
{
cout << element;
}
else if (std::is_same<T, my_class>::value)
{
element->print(); // Would not compile when T is int!
}
Also, as Xeo correctly pointed out in the comments, the compiler will likely issue warnings because your condition will always evaluate to true
or to false
, so one of the two branches will contain unreachable code.