开发者

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

#include <iostream>
#i开发者_C百科nclude <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.


I bet it's creating the bound function as a variadic function, like printf.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜