Skip to content

Instantly share code, notes, and snippets.

@eahydra
Last active December 14, 2015 17:28
Show Gist options
  • Save eahydra/5122295 to your computer and use it in GitHub Desktop.
Save eahydra/5122295 to your computer and use it in GitHub Desktop.
#ifndef ASYNC_EXTEND_HPP_
#define ASYNC_EXTEND_HPP_
#include <future>
namespace base {
namespace detail {
template<typename future_t, typename handler_t>
struct async_helper {
static auto async_impl(std::launch::launch policy, future_t f, handler_t&& handler, std::true_type)->std::future<decltype(handler(f))>
{
return std::async(policy, [=]() { handler(f); });
}
static auto async_impl(std::launch::launch policy, future_t f, handler_t&& handler, std::false_type)->std::future<decltype(handler(f))>
{
return std::async(policy, [=]()->decltype(handler(f)){ return handler(f); });
}
static auto async(std::launch::launch policy, future_t f, handler_t&& handler)->std::future<decltype(handler(f))>
{
typedef decltype(handler(f)) return_t;
return async_impl(policy, f, std::move(handler), std::is_void<return_t>());
}
};
} // namespace detail
template <typename future_t, typename handler_t>
auto then(future_t f, handler_t&& handler)->std::future<decltype(handler(f))> {
return then(std::launch::any, f, std::move(handler));
}
template <typename future_t, typename handler_t>
auto then(std::launch::launch policy, future_t f, handler_t&& handler)->std::future<decltype(handler(f))>
{
return detail::async_helper<future_t, handler_t>::async(policy, f, std::move(handler));
}
}
#if TEST
void test_async_extend()
{
std::future<int> f1 = std::async(std::launch::async, []()->int{
std::cout<<__FUNCTION__<<std::endl;
return 123;
});
std::future<bool> f2 = base::then(f1.share(), [](std::shared_future<int> fut)->bool{
std::cout<<__FUNCTION__<<std::endl;
std::cout<<"f1.get() = "<<fut.get()<<std::endl;
return true;
});
std::future<void> f3 = base::then(f2.share(), [](std::shared_future<bool> fut){
std::cout<<__FUNCTION__<<std::endl;
std::cout<<"f2.get() = "<<fut.get()<<std::endl;
return;
});
f3.wait();
}
#endif
#endif // ASYNC_EXTEND_HPP_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment