[英]Is there a way to use std::async with std::experimental::future?
注意:即使在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
:
std::future
std:experimental::future
但是, std::async
僅返回std::future
,因此上面的代碼是非法的。 如果std::async
返回std:experimental::future
,那就沒關系。
我的問題是:
有沒有辦法在std::experimental::future
中使用std::async
,使得代碼在C ++ 1z下面合法?
有沒有辦法在
std::experimental::future
中使用std::async
,使得代碼在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
這樣的其他啟動策略,但它只是一個開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.