我正在尝试使用 packaged_task 实现异步。我正在通过模板函数 bsync 尝试此操作。bsync 接受 2 个参数:一个函数 f 和一个参数包 args,并返回一个未来 fut。未来是 f(args...) 返回的类型。即 - 回报是未来
我想我快到了,但是我遇到了类型转换错误。任何帮助,将不胜感激:
#include "stdafx.h"
#include <iostream>
#include <future>
#include <thread>
#include <functional>
#include <type_traits>
using namespace std;
//Implement bsync as a templated function
//Template parameters are (i) Fn (the function to run), (ii) Args, a parameter pack of arguments to feed the function
//The function returns a future<Ret>, where Ret is the return-type of Fn(Args)
template<class Fn,class...Args>
auto bsync(Fn f, Args&&...args)->future<result_of<decltype(f)&(Args&&...)>>{
//Determine return-type
typedef result_of<decltype(f)&(Args&&...)>::type A;
//Initialize a packaged_task
packaged_task <A(Args&&...)>tsk(f);
//Initialize a future
future<A> fut = tsk.get_future();
//Run the packaged task in a separate thread
thread th(move(tsk),(args)...);
//Join the thread
th.join();
return fut;
}
int plus_one(int x){
cout << "Adding 1 to " << x << endl;
return x++;
}
int main(){
auto x = bsync(plus_one, 1);
cout << "Press any key to continue:" << endl;
cin.ignore();
return 0;
}