为什么可以用额外的参数调用Boost.Bind函数? [英] Why can a Boost.Bind function be called with extra parameters?

查看:148
本文介绍了为什么可以用额外的参数调用Boost.Bind函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <string>

#include <boost/bind.hpp>

void foo(std::string const& dummy)
{
    std::cout << "Yo: " << dummy << std::endl;
}

int main()
{
    int* test;
    std::string bar("platypus");
    (boost::bind(&foo, bar))(test, test, test, test, test, test, test, test);
}

运行时会打印出Yo:platypus。它似乎完全忽略了额外的参数。我希望得到一个编译错误。我不小心通过这种方式向我的代码中引入了一个bug。

When run, it prints out, "Yo: platypus." It appears to completely ignore extra parameters. I'd expect to get a compile error. I accidentally introduced a bug into my code this way.

推荐答案

我不知道为什么允许这样做,但我知道它是预期的行为。从此处

I don't know why this is allowed, but I do know it is expected behavior. From here:


bind可以处理多于
的函数,而不是两个参数,它的参数
替换机制更多
general:

bind can handle functions with more than two arguments, and its argument substitution mechanism is more general:

bind(f, _2, _1)(x, y);                 // f(y, x)
bind(g, _1, 9, _1)(x);                 // g(x, 9, x)
bind(g, _3, _3, _3)(x, y, z);          // g(z, z, z)
bind(g, _1, _1, _1)(x, y, z);          // g(x, x, x)

请注意,在最后一个例子中,$ b由bind(g,
_1,_1,_1)生成的$ b函数对象不包含对任何超出
的参数的引用,但它仍然可以与
多于一个参数一起使用。 任何额外的
参数都会默默忽略
(重点是我的),只是
像第一个和第二个参数
在第三个示例中被忽略。

Note that, in the last example, the function object produced by bind(g, _1, _1, _1) does not contain references to any arguments beyond the first, but it can still be used with more than one argument. Any extra arguments are silently ignored (emphasis mine), just like the first and the second argument are ignored in the third example.

这篇关于为什么可以用额外的参数调用Boost.Bind函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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