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;
});
}