gpt4 book ai didi

c++:使用 packaged_task 构建异步

转载 作者:搜寻专家 更新时间:2023-10-31 01:40:15 25 4
gpt4 key购买 nike

我正在尝试使用 packaged_task 实现异步。我正在通过一个模板化函数 bsync 来尝试这个。 bsync 接受 2 个参数:一个函数 f 和一个参数包 args,并返回一个 future fut。 future 是 f(args...) 返回的类型。即 - 返回是 future 的

我想我快完成了,但是我遇到了类型转换错误。任何帮助将不胜感激:

#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&&...)>>

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

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

一旦你解决了这个问题,你就错过了一个 typename在你的typedef对于 A .

关于c++:使用 packaged_task 构建异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30034461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com