Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a template function compare the two typenames? [duplicate]

Tags:

c++

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?

like image 746
Hailiang Zhang Avatar asked Nov 30 '12 22:11

Hailiang Zhang


2 Answers

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 ...;
}
like image 119
CygnusX1 Avatar answered Sep 18 '22 11:09

CygnusX1


#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

like image 6
template boy Avatar answered Sep 20 '22 11:09

template boy