简体   繁体   English

具有不同签名的绑定功能

[英]Binding functions with different signatures

If this question has been asked, I apologize. 如果问过这个问题,我道歉。

I thought you couldn't bind functions with a different signature, but look at this: 我以为你不能用不同的签名绑定函数,但看看这个:

void TakesChar(char parameter)
{
    std::cout << parameter << std::endl;
}

using CallSig = void(float);
using CallBack = std::function<CallSig>;

int main()
{
    CallBack callback = std::bind(&TakesChar, std::placeholders::_1);
    callback(1.1f);
    callback(2.2f);

    return 0;
}

That compiles and runs. 编译并运行。 You can try different parameter types and numbers. 您可以尝试不同的参数类型和数字。 You can, for instance, modify TakesChar so that it takes no parameters, and it will still compile. 例如,您可以修改TakesChar ,使其不带参数,并且仍然可以编译。

Why is this? 为什么是这样? Is there a rationale behind it? 它背后有理由吗? And can I enforce signatures to match exactly? 我可以强制签名完全匹配吗?

Thanks. 谢谢。

Actually, there are two questions here: 实际上,这里有两个问题:

  1. Why is conversion allowed ? 为什么允许转换?
  2. Why if no argument is provided to bind , the return object accepts any number of argument ? 为什么如果没有提供bind参数,返回对象是否接受任意数量的参数?

The former is just a decision on the behavior of bind : since you can call TakesChar(1.1f) why not allow std::bind(&TakesChar, _1) to bind to std::function<void(float)> ? 前者只是对bind行为的决定:因为你可以调用TakesChar(1.1f)为什么不允许std::bind(&TakesChar, _1)绑定到std::function<void(float)> The committee decided to allow it. 委员会决定允许它。

The latter, as explained in comments, was already addressed on SO . 正如评论中所解释的那样,后者已在SO上得到解决。 In short, not only is it easier, it also allows to bind an object that has multiple operator() of different arities. 简而言之,它不仅更容易,还允许bind具有多个不同arity的operator()的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM