gpt4 book ai didi

c++ - 为什么 "std::async"没有按预期工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:38 33 4
gpt4 key购买 nike

#include <thread>
#include <functional>
#include <utility>

using namespace std;

template<typename Callable, typename... Args>
void Async(Callable&& fn, Args&&... args)
{
auto fn_wrapper = [](Callable&& fn, Args&&... args)
{
invoke(forward<Callable>(fn), forward<Args>(args)...);
};

// ok
fn_wrapper(forward<Callable>(fn), forward<Args>(args)...);

// ok
async(forward<Callable>(fn), forward<Args>(args)...);

// error : no matching function for call to 'async'
async(fn_wrapper, forward<Callable>(fn), forward<Args>(args)...);
}

void f(int, int) {}

int main()
{
Async(f, 1, 2);
this_thread::sleep_for(1min);
}

下面的代码就可以了:

  fn_wrapper(forward<Callable>(fn), forward<Args>(args)...);

下面的代码也可以:

  async(forward<Callable>(fn), forward<Args>(args)...);

但是,下面的代码是的:

  // error : no matching function for call to 'async'
async(fn_wrapper, forward<Callable>(fn), forward<Args>(args)...);

最后一个案例编译失败,出现如下错误:

main.cpp:27:5: fatal error: no matching function for call to 'async'
async(fn_wrapper,
^~~~~
main.cpp:36:5: note: in instantiation of function template specialization 'Async<void (&)(int, int), int, int>' requested here
Async(f, 1, 2);
^

[...]

/usr/local/bin/../lib/gcc/x86_64-pc-linux-gnu/6.3.0/../../../../include/c++/6.3.0/future:1739:5: note: candidate template ignored: substitution failure [with _Fn = (lambda at main.cpp:12:9) &, _Args = <void (&)(int, int), int, int>]: no type named 'type' in 'std::result_of<(lambda at main.cpp:12:9) (void (*)(int, int), int, int)>'
async(_Fn&& __fn, _Args&&... __args)

为什么最后一个案例不起作用?

最佳答案

完美转发 ( && ) 仅适用于模板参数上下文。但是您的 lambda 不是模板。所以(Callable&& fn, Args&&... args)只是打耳光&&到每个参数上,实际上意味着“通过右值引用传递”,这不会正确地完美转发。

但更重要的是,std::async将仿函数称为 INVOKE(DECAY(std::forward<F>(f)), DECAY(std::forward<Args>(args))...) , 所以推导的仿函数的参数类型实际上是衰减 CallableArgs .

试试这个包装器:

    auto fn_wrapper = [](auto&& fn, auto&&... args)
{
invoke(forward<decltype(fn)>(fn), forward<decltype(args)>(args)...);
};

关于c++ - 为什么 "std::async"没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42156726/

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