gpt4 book ai didi

c++ - 有没有办法将 std::async 与 std::experimental::future 一起使用?

转载 作者:太空狗 更新时间:2023-10-29 21:13:49 24 4
gpt4 key购买 nike

注意:即使在 C++17 中,以下内容也是非法的!

#include <thread>
#include <future>
#include <experimental/future>

using namespace std;

int step1(experimental::future<int>)
{
return {};
}

int step2(experimental::future<int>)
{
return {};
}

int step3(experimental::future<int>)
{
return {};
}

int main()
{
return async([](){ return {}; })
.then(step1)
.then(step2)
.then(step3)
.get();
}

C++1z 提供了两种future:

  1. std::future
  2. std:experimental::future

但是,std::async 只返回std::future,所以上面的代码是非法的。如果 std::async 返回 std:experimental::future,那么就可以了。

我的问题是:

有没有一种方法可以将 std::asyncstd::experimental::future 一起使用,从而使上述代码在 C++1z 下合法?

最佳答案

Is there a way to use std::async with std::experimental::future that makes the code above legal under C++1z?

没有。 std::async返回 std::future<T>尽管有名称,但它是与 std::experimental::future<T> 完全无关的类型.

您必须编写自己的 async 版本这给了你一种新的 future .一个简化的版本是这样的:

template <class F, class... Args,
class R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>
std::experimental::future<R> new_async(F&& f, Args&&... args)
{
std::experimental::promise<R> p;
auto fut = p.get_future();

std::thread thread([p=std::move(p), f=std::forward<F>(f),
args=std::tuple<std::decay_t<Args>...>(std::forward<Args>(args)...)] () mutable
{
try
{
if constexpr(std::is_void_v<R>)
{
std::apply(std::move(f), std::move(args));
p.set_value();
}
else
{
p.set_value(std::apply(std::move(f), std::move(args)));
}
}
catch(...)
{
p.set_exception(std::current_exception());
}
});

thread.detach();
return fut;
}

这不支持其他启动策略,例如 async确实如此,但这只是一个开始。

关于c++ - 有没有办法将 std::async 与 std::experimental::future 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42831639/

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