代码之家  ›  专栏  ›  技术社区  ›  Joseph Garvin

为什么可以用额外的参数调用boost.bind函数?

  •  7
  • Joseph Garvin  · 技术社区  · 16 年前
    #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。

    2 回复  |  直到 16 年前
        1
  •  2
  •   SCFrench    16 年前

    我不知道为什么允许这样做,但我知道这是预期行为。从 here :

    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)不包含对除 首先,但它仍然可以与 多个参数。 任何额外 参数被静默忽略 (强调我的),只是 就像第一个和第二个论点 在第三个示例中被忽略。

        2
  •  0
  •   Brooks Moses    16 年前

    我敢打赌它正在创建一个变量函数的绑定函数,比如 printf .