简体   繁体   English

C ++ 11异步+然后

[英]C++11 async + then

I've tried to compile this (with some small obvious fixes) c++11 async continuations or attempt at .then() semantics using clang (latest version) with libc++ and it won't compile: No matching function for call to 'then'. 我尝试使用clang(最新版本)和libc ++来编译c ++ 11异步延续或尝试使用.then()语义 (并进行一些小小的明显修正) 并且不会编译:没有匹配的函数可用于调用'然后'。

I couldn't find the reason... Can you help me in this? 我找不到原因...您能帮我吗?

The answer is lacking move in a few places. 答案是在某些地方缺乏move Without the moves, future is being asked to copy, which it can't because it is a move-only type. 没有移动,就要求复制future ,因为它是仅移动类型,所以不能复制。

#include <future>

namespace detail
{

template<typename F, typename W, typename R>
struct helper
{
    F f;
    W w;

    helper(F f, W w)
        : f(std::move(f))
        , w(std::move(w))
    {
    }

    helper(const helper& other)
        : f(other.f)
        , w(other.w)
    {
    }

    helper(helper&& other)
        : f(std::move(other.f))
        , w(std::move(other.w))
    {
    }

    helper& operator=(helper other)
    {
        f = std::move(other.f);
        w = std::move(other.w);
        return *this;
    }

    R operator()()
    {
        f.wait();
        return w(std::move(f)); 
    }
};

}  // detail

template<typename F, typename W>
auto then(F f, W w) -> std::future<decltype(w(std::move(f)))>
{ 
    return std::async(std::launch::async,
      detail::helper<F, W, decltype(w(std::move(f)))>(std::move(f),
                                                      std::move(w))); 
}

int
test()
{
    return 1;
}

int
main()
{
    std::future<int> f = std::async(test);
    auto f2 = then(std::move(f), [](std::future<int> f)
    {
        return f.get() * 2; 
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM