C++11 异步 + 然后

标签 c++ asynchronous c++11 future

我试过编译这个(有一些明显的小修复) c++11 async continuations or attempt at .then() semantics 将 clang(最新版本)与 libc++ 一起使用,它不会编译:没有匹配的函数来调用“then”。

我找不到原因...你能帮我解决这个问题吗?

最佳答案

答案是在一些地方缺少move。如果没有移动,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; 
    });
}

关于C++11 异步 + 然后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16208147/

相关文章:

c++ - 优雅地捕获 LoadLibrary() 错误

javascript - 如何在node.js中同步运行这个函数

c++ - 需要正则表达式来定位名称未知的 C++ 命名空间声明

javascript - 在同步函数和 for 循环中获取 API

javascript - 为什么如果 `$q.all` 没有返回一个 Promise 数组,那么不会抛出异常吗?

c++ - constexpr 函数的 undefined symbol

types - nullptr 的强类型化?

multithreading - 在 C++ 多线程应用程序中,我应该传递 lambda 还是带参数的函数?

c++ - 使用继承来添加功能

c++ - 我在比较字符数组中的字符时遇到问题