是否可以编写C ++模板/宏来检查两个函数是否具有相同的签名 [英] Is it possible to write c++ template/macros to check whether two functions have the same signatures

查看:117
本文介绍了是否可以编写C ++模板/宏来检查两个函数是否具有相同的签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以编写c ++模板/宏来检查两个函数是否具有相同的签名(返回类型和参数列表)?

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 ?

PS
实际上我对c ++ 2003标准很感兴趣。

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

推荐答案

C ++ 11解决方案


无需自己编写任何模板。

C++11 Solution

No need to write any template yourself.

您可以将 decltype std :: is_same

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;
}

此处 decltype 返回类型(在这种情况下为函数),以及 std :: is_same 比较两个类型,如果两者相同,则返回 true ,否则 false

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中,您没有 decltype ,因此可以实现重载的函数模板,如下所示:

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;
}

现在在这种情况下, is_same 是功能模板,而不是类模板。因此,它是在运行时而不是编译时进行评估的。因此,这将产生错误:

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))

现在将其用作:

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

希望有帮助。

这篇关于是否可以编写C ++模板/宏来检查两个函数是否具有相同的签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆