How to check if two template parameters are the same?

Apr 7, 2012 at 9:00am
Hi all, suppose i have a template class:

template<typename T> my_class{...};

and a template function that makes some checks on two my_class objects

1
2
template<typename T1, typename T2> 
bool some_checks(const my_class<T1>& c1, const my_class<T2>& c2){...}


is there a way to check if T1==T2?

or i have to write another some_check funtion like this:

1
2
template<typename T> 
bool some_checks(const my_class<T>& c1, const my_class<T>& c2){...}


Thanks!

Last edited on Apr 7, 2012 at 9:16am
Apr 7, 2012 at 9:09am
If a == cannot be derived implicity, then yes you will need to provide an implementation.
Apr 7, 2012 at 9:23am
is there a way to check if T1==T2?
1
2
3
4
5
6
7
8
9
10
11
12
template<typename T, typename T2>
bool some_checks(const my_class<T>& c1, const my_class<T2>& c2)
{
if(typeid(T)==typeid(T2))
  {
      cout <<" T1==T2"<<endl;
  }
 else
 {
     cout <<"T1!=T2"<<endl;
 }
}
Last edited on Apr 7, 2012 at 9:23am
Apr 7, 2012 at 9:45am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
namespace home_grown
{
    struct true_type {} ;
    struct false_type {} ;

    template< typename A, typename B > struct is_same
    {
        enum { value = false } ;
        typedef false_type type ;
    };

    template< typename A > struct is_same<A,A>
    {
        enum { value = true } ;
        typedef true_type type ;
    };
}

template< typename A, typename B > void foo( /* ... */ )
{
    enum { SAME_TYPE = std::is_same<A,B>::value } ; // C++11

    // C++98: #include <boost/type_traits.hpp>
    enum { SAME_TYPE_98 = boost::is_same<A,B>::value } ;

    // if libstdc++ or boost can't be used
    enum { SAME_TYPE_HG = home_grown::is_same<A,B>::value } ;
}


Consider using SFINAE: std::enable_if<>, boost::enable_if<> or a home_grown::enable_if<>
Topic archived. No new replies allowed.