Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Quickly Check whether C++ Template Instances have the Same Parameters

5.00/5 (2 votes)
7 Feb 2012CPOL 10.8K  
How to quickly check whether C++ Template Instances have the same parameters

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:

C++
#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:

C++
#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;
 
    // This would raise a compiler error:
    // std::cout << "Type of a equals d: " << has_same_parameter_type(a, d)  << std::endl;

    char ch;
    std::cin >> ch;
    return 0;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)