Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write c++ template/macros to check whether two functions have the same signatures

Is it possible to write c++ template/macros to check whether two functions have the same signatures (return type and arguments list) ?

Here's a simple example of how I want to use it:

int foo(const std::string& s) {...}
int bar(const std::string& s) {...}

if (SAME_SIGNATURES(foo, bar))
{
    // do something useful... make Qt signal-slot connection for example...
}
else
{
    // signatures mismatch.. report a problem or something...
}

So is it possible somehow or is it just a pipe dream ?

P.S. Actually I'm interesting in c++ 2003 standard.

like image 893
sergeyz Avatar asked Nov 30 '22 01:11

sergeyz


1 Answers

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.

like image 77
Nawaz Avatar answered Dec 10 '22 10:12

Nawaz