C++11 解决方案
无需自己编写任何模板。
您可以将decltype 与std::is_same 一起使用:
if (std::is_same<decltype(foo),decltype(bar)>::value )
{
std::cout << "foo and bar has same signature" << std::endl;
}
这里decltype返回表达式的类型,在这种情况下是函数,std::is_same比较两个类型,如果两者都返回true相同,否则false。
C++03解决方案
在C++03中,你没有decltype,所以你可以实现重载的函数模板为:
template<typename T>
bool is_same(T,T) { return true; }
template<typename T, typename U>
bool is_same(T,U) { return false; }
现在您可以将其用作:
if (is_same(foo, bar))
{
std::cout << "foo and bar has same signature" << std::endl;
}
现在在这种情况下is_same 是一个函数模板,而不是类模板。所以它在运行时而不是编译时进行评估。所以这会报错:
int a[is_same(foo,bar) ? 10 : 20]; //error (in Standard C++03)
//the size must be known at compile-time!
但是,如果您需要在编译时了解它,那么您必须做更多工作,并将功能实现为:
typedef char same[1];
typedef char different[2];
template<typename T>
same& is_same_helper(T,T); //no need to define it now!
template<typename T, typename U>
different& is_same_helper(T,U); //no definition needed!
#define is_same(x,y) (sizeof(is_same_helper(x,y)) == sizeof(same))
现在将其用作:
if (is_same(foo, bar))
{
std::cout << "foo and bar has same signature" << std::endl;
}
您也可以在编译时使用它。这样你就可以写了:
int a[is_same(foo,bar) ? 10 : 20]; //okay
希望对您有所帮助。