簡體   English   中英

有沒有辦法在std :: experimental :: future中使用std :: async?

[英]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

  1. std::future
  2. 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這樣的其他啟動策略,但它只是一個開始。

看起來像 std::experimental::future具有相同的構造為std::future ,所以它應該是可以構建一個std::experimental::futurestd::future 然而,正如ildjarn指出的那樣 ,它實際上並不是根據最新的草案 ,所以在TS相應改變之前似乎沒有辦法做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM