繁体   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);
}

在跑步时,打印出“Yo:platypus”。 它似乎完全忽略了额外的参数。 我希望得到一个编译错误。 我不小心以这种方式向我的代码中引入了一个错误。

我不知道为什么这是允许的,但我确实知道这是预期的行为。 这里

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) 

请注意,在最后一个示例中,bind(g,_1,_1,_1)生成的函数对象不包含对第一个参数之外的任何参数的引用,但它仍可以与多个参数一起使用。 任何额外的参数都会被默默忽略 (强调我的),就像在第三个例子中忽略第一个和第二个参数一样。

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

暂无
暂无

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

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