C++:与packaged_task异步构建

c++: Building async with packaged_task

本文关键字:task 异步 构建 packaged C++      更新时间:2023-10-16

我正在尝试与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;
}

尾随返回类型不正确。你有:

future<result_of<decltype(f)&(Args&&...)>>

这是一个类型为result_of<...>future。您需要实际评估result_of元函数以生成实际的结果类型。那是:

future<typename result_of<Fn(Args&&...)>::type>
^^^^^^^^^                        ^^^^^^

一旦你解决了这个问题,你的typedef中就会缺少一个typenameA