1

为什么以下代码中的嵌套没有被任何主要编译器(VS2010/2012、gcc、clang)std::bind隐式转换为an ?std::function<void()>这是标准行为还是错误?

#include <functional>

void bar(int, std::function<void()>) { }
void foo() { }

int main()
{
    std::function<void(int, std::function<void()>)> func;
    func = std::bind(bar, 5, std::bind(foo));

    std::cin.get();
    return 0;
}
4

1 回答 1

4

这在boost 文档中进行了解释:

调用函数对象时,内部绑定表达式在外部绑定之前以未指定的顺序进行评估;然后在评估外部绑定时将评估结果替换为它们的位置。在上面的示例中,当使用参数列表 (x) 调用函数对象时,首先计算 bind(g, _1)(x),产生 g(x),然后是 bind(f, g(x))( x) 被评估,产生最终结果 f(g(x))。

Boost 甚至提供protect了防止这种评估的方法:

#include <boost/bind/protect.hpp>
...
func = std::bind(bar, 5, boost::protect(std::bind(foo)));

但是,要打电话给func你必须提供这样的两个论点(感谢David Rodríguez - dribeas指出了这一点),所以这个例子绝对不好:

func(1, std::function<void()>());
于 2012-11-28T23:01:57.440 回答