为什么以下代码中的嵌套std::bind
未被任何主要编译器(VS2010 / 2012,gcc,clang)隐式转换为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;
}
答案 0 :(得分:4)
之前以未指定的顺序计算内部绑定表达式 调用函数对象时的外部绑定;结果 然后在外部绑定时将评估替换为它们的位置 评价即可。在上面的示例中,调用函数对象时 使用参数列表(x),首先计算bind(g,_1)(x), 产生g(x),然后结合(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()>());