Note: From Sebastian's tip, it does not seem clear to me if only the template parameter type should be checked or also its value. He might want to check type and value without raising compiler errors. My alternative only deals with the template parameter types.
If RTTI is not present, you can still use the typeid
keyword. My contribution to this topic is then as follows:
#include <iostream>
template<class T>
class my_template
{
public:
template<class T2>
bool type_equals(const T2& o) const
{
return typeid(*this) == typeid(o);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
my_template<int> a;
my_template<double> b;
my_template<int> c;
std::cout << std::boolalpha;
std::cout << "Type of a equals a: " << a.type_equals(b) << std::endl;
std::cout << "Type of a equals c: " << a.type_equals(c) << std::endl;
char ch;
std::cin >> ch;
return 0;
}
For the fun of it, you can also use the std::is_same
template:
#include <iostream>
template<class T>
class my_template
{
public:
typedef T parameter_type;
};
template<class T1, class T2>
bool has_same_parameter_type(const my_template<T1>& o1, const my_template<T2>& o2)
{
return std::is_same<T1, T2>::value;
}
int _tmain(int argc, _TCHAR* argv[])
{
my_template<int> a;
my_template<double> b;
my_template<int> c;
std::string d;
std::cout << std::boolalpha;
std::cout << "Type of a equals a: " << has_same_parameter_type(a, b) << std::endl;
std::cout << "Type of a equals c: " << has_same_parameter_type(a, c) << std::endl;
char ch;
std::cin >> ch;
return 0;
}