12

Possible Duplicate:
Program to implement the is_same_type type trait in c++

I want my template function to do something differently based on whether the two typenames are equal or not:

template <typename T1, typename T2> f()
{
  if (T1==T2) ...;
  else ...;
}

I know "if(T1==T2)" is not gonna working, but, is there a way to do it?

Community
  • 1
  • 1
Hailiang Zhang
  • 17,604
  • 23
  • 71
  • 117
  • 1
    http://en.cppreference.com/w/cpp/types/is_same – SplinterOfChaos Nov 30 '12 at 22:52
  • 1
    @NPE this is not a duplicate IMHO. Properly applying `is_same` is different from just implementing it. What if he will be doing `T2 t; T1 *u = &t;` in the true branch? Compilation will fail if he uses above `if` for types `char` and `int` respectively. – Johannes Schaub - litb Nov 30 '12 at 23:16
  • @JohannesSchaub-litb: You're right. Can't undo the vote, but will cease casting close votes for the rest of the day. :) – NPE Nov 30 '12 at 23:19

5 Answers5

18

You can check the boost::is_same or std::is_same in C++11.

So, it would be something like this:

template <typename T1, typename T2> f()
{
  if (boost::is_same<T1,T2>::value) ...;
  else ...;
}
CygnusX1
  • 20,968
  • 5
  • 65
  • 109
6
#include <type_traits>

template <typename A, typename B> void f() {

    if ( std::is_same<A, B>::value ) {

        //

    }

}

std::is_same returns a typedef of a boolean (true, false) depending on the equlity of the types A and B

template boy
  • 10,230
  • 8
  • 61
  • 97
4

If the types can be inferred and are not being explicitly passed, you could make two separate functions:

template<typename SameType>
void f(SameType x, SameType y)
{
    // ...
}

template<typename T1, typename T2>
void f(T1 x, T2 y)
{
    // ...
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
1

Specialize the template

template<typename T1, typename T2>
void f()
{
  //The else part goes here
}

template<typename T>
void f()
{
  //The if part goes here
}
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0

You can compare the typeid of T1 and T2

#include <typeinfo>

template <typename T1, typename T2> void f()
{
    bool a;
    if (typeid(T1) == typeid(T2))
        a = true;
    else
        a = false;
}
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • 1
    While it is also a solution, note that typeid is resolved at run time. It introduces performance overhead and both branches will be present in the function. I believe the compile-time evaluation of the condition is preferred. – CygnusX1 Nov 30 '12 at 22:58
  • 2
    And it will not work for `f` or `f` since the typeid for all of them is equal. – Johannes Schaub - litb Nov 30 '12 at 23:01