简体   繁体   中英

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." 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(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. Any extra arguments are silently ignored (emphasis mine), just like the first and the second argument are ignored in the third example.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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