I want use .net's System.Threading.Tasks.Task.ContinueWith
in C++, so I write the following function..
#include <iostream>
#include <functional>
#include <future>
template <typename Func, typename Ret>
auto continue_with(std::future<Ret> &&fu, Func func)
-> std::future<decltype(func(fu.get()))>
{
return std::async(
[fu = std::move(fu), func]() mutable { return func(fu.get()); }
);
}
template <typename Func>
auto continue_with(std::future<void> &&fu, Func func)
-> std::future<decltype(func())>
{
return std::async(
[fu = std::move(fu), func]() mutable { fu.get(); return func(); }
);
}
int main()
{
std::future<void> fu = std::async([]{ std::cout << "fu" << std::endl; });
std::future<void> fu2 = continue_with(
std::move(fu),
[]{ std::cout << "fu2" << std::endl; }
);
fu2.get();
std::cout << "fu continue complete" << std::endl;
std::future<int> retfu = std::async([]{ std::cout << "retfu" << std::endl; return 3; });
std::future<int> retfu2 = continue_with(
std::move(retfu),
[](int result){ std::cout << "retfu2 " << result << std::endl; return result + 1; }
);
int ret = retfu2.get();
std::cout << "retfu continue complete : " << ret << std::endl;
std::cin.get();
}
This code works on gcc 4.8.2 with -std=c++1y
. (I don't know why, but it works with -std=c++11
, too)
But it doesn't work on VC++ 2013. I guess it's because init-capture, a C++14 feature. How can I run this code with VC++ 2013?
(I want to use lambda, so please don't tell me "use just function-object struct!")
(I tried Move capture in lambda, but it doesn't work..)
(I'll appreciate if you not only answer my question but also imporve my code)