C++11 Solution
No need to write any template yourself.
You can use decltype
along with std::is_same
:
if (std::is_same<decltype(foo),decltype(bar)>::value )
{
std::cout << "foo and bar has same signature" << std::endl;
}
Here decltype
returns the type of the expression which is function in this case, and std::is_same
compares the two types, and returns true
if both are same, else false
.
C++03 Solution
In C++03, you don't have decltype
, so you can implement overloaded function templates as:
template<typename T>
bool is_same(T,T) { return true; }
template<typename T, typename U>
bool is_same(T,U) { return false; }
Now you can use it as:
if (is_same(foo, bar))
{
std::cout << "foo and bar has same signature" << std::endl;
}
Now that in this case is_same
is a function template, not class template. So it is evaluated at runtime as opposed to compile-time. So this will give error:
int a[is_same(foo,bar) ? 10 : 20]; //error (in Standard C++03)
//the size must be known at compile-time!
However, if you need to know it at compile-time, then you've to work more, and implement the functionality as:
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))
Now use it as:
if (is_same(foo, bar))
{
std::cout << "foo and bar has same signature" << std::endl;
}
You can use it at compile-time also. so you can write it:
int a[is_same(foo,bar) ? 10 : 20]; //okay
Hope that helps.