【问题标题】:Why can a Boost.Bind function be called with extra parameters?为什么可以使用额外参数调用 Boost.Bind 函数?
【发布时间】:2011-03-20 06:23:11
【问题描述】:
#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”。它似乎完全忽略了额外的参数。我希望得到一个编译错误。我不小心以这种方式在我的代码中引入了一个错误。

【问题讨论】:

    标签: c++ boost functional-programming compiler-errors


    【解决方案1】:

    我不知道为什么允许这样做,但我知道这是预期的行为。来自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) 不包含对任何参数的引用 首先,但它仍然可以与 不止一个论点。 任何额外的 参数被默默地忽略(强调我的),只是 像第一个和第二个参数 在第三个示例中被忽略。

    【讨论】:

    • 如果有人发现,我仍然很想知道为什么允许这种行为的原因:)
    • @Joseph:可能太复杂,无法明确禁止。
    【解决方案2】:

    我敢打赌,它会将绑定函数创建为可变参数函数,例如 printf

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-25
    • 2018-12-06
    • 1970-01-01
    • 2022-12-03
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多