Can a template function compare the two typenames?

2020-07-08 08:03发布

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?

标签: c++
5条回答
Fickle 薄情
2楼-- · 2020-07-08 08:14

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;
}
查看更多
Deceive 欺骗
3楼-- · 2020-07-08 08:17

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 ...;
}
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-07-08 08:32

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
}
查看更多
我只想做你的唯一
5楼-- · 2020-07-08 08:35
#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

查看更多
一夜七次
6楼-- · 2020-07-08 08:38

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)
{
    // ...
}
查看更多
登录 后发表回答