gpt4 book ai didi

c++ - 为什么这个 std::bind 没有转换为 std::function?

转载 作者:行者123 更新时间:2023-11-30 02:02:03 25 4
gpt4 key购买 nike

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

#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;
}

最佳答案

这在 boost documentation 中有解释:

The inner bind expressions are evaluated, in unspecified order, before the outer bind when the function object is called; the results of the evaluation are then substituted in their place when the outer bind is evaluated. In the example above, when the function object is called with the argument list (x), bind(g, _1)(x) is evaluated first, yielding g(x), and then bind(f, g(x))(x) is evaluated, yielding the final result 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()>());

关于c++ - 为什么这个 std::bind 没有转换为 std::function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13615873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com