1

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'.

I couldn't find the reason... Can you help me in this?

Community
  • 1
  • 1
stoflow
  • 163
  • 1
  • 10

1 Answers1

2

The answer is lacking move in a few places. Without the moves, future is being asked to copy, which it can't because it is a move-only type.

#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; 
    });
}
Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577