简体   繁体   English

为什么可以使用额外的参数调用Boost.Bind函数?

[英]Why can a Boost.Bind function be called with extra parameters?

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

When run, it prints out, "Yo: platypus." 在跑步时,打印出“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 can handle functions with more than two arguments, and its argument substitution mechanism is more general: bind可以处理具有两个以上参数的函数,其参数替换机制更通用:

 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) 

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. 请注意,在最后一个示例中,bind(g,_1,_1,_1)生成的函数对象不包含对第一个参数之外的任何参数的引用,但它仍可以与多个参数一起使用。 Any extra arguments are silently ignored (emphasis mine), just like the first and the second argument are ignored in the third example. 任何额外的参数都会被默默忽略 (强调我的),就像在第三个例子中忽略第一个和第二个参数一样。

我敢打赌它正在创建绑定函数作为可变参数函数,如printf

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

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