C++ c++;:使用打包的_任务构建异步
我正在尝试使用打包的_任务实现异步。我试图通过一个模板函数bsync实现这一点。bsync接受两个参数:函数f和参数包args,并返回future fut。future是由f(args…)返回的类型。Ie-回报是未来 我想我快到了,但是我得到了一个类型转换错误。如有任何帮助,将不胜感激:C++ c++;:使用打包的_任务构建异步,c++,multithreading,templates,c++11,packaged-task,C++,Multithreading,Templates,C++11,Packaged Task,我正在尝试使用打包的_任务实现异步。我试图通过一个模板函数bsync实现这一点。bsync接受两个参数:函数f和参数包args,并返回future fut。future是由f(args…)返回的类型。Ie-回报是未来 我想我快到了,但是我得到了一个类型转换错误。如有任何帮助,将不胜感激: #include "stdafx.h" #include <iostream> #include <future> #include <thread> #include &l
#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;
}
#包括“stdafx.h”
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
//将bsync作为模板函数实现
//模板参数是(i)Fn(要运行的函数),(ii)Args,一组参数,用于为函数提供参数
//函数返回一个future,其中Ret是Fn(Args)的返回类型
模板
自动同步(Fn f,Args&…Args)->未来{
//确定退货类型
typedef result_of::类型A;
//初始化打包的任务
打包任务tsk(f);
//初始化未来
future fut=tsk.get_future();
//在单独的线程中运行打包的任务
线程th(移动(tsk),(参数);
//接线
th.join();
返回fut;
}
整数加一(整数x){
cout您的尾部返回类型不正确。您有:
future<result_of<decltype(f)&(Args&&...)>>
一旦你解决了这个问题,你的typedef
中缺少了typename
,这是a
的第一个突出问题:future
。你的意思是future
?(另外,既然你有Fn
,我不知道你为什么要使用decltype(f)
)另外,请检查编译器是否提供了C++14result\u of\u t
。几乎就在那里-查看主函数。我可以成功地向bsync传递一个arg&&,但不能传递一个arg。例如:这可以工作:int y=1;auto x=bsync(plus\u one,y);这不起作用:auto x=bsync(plus\u one,1);我猜我的实现在引用地狱的某个地方-有什么想法吗?@ice\u planet\u hoth\u boss我想你的意思是相反的。这是因为线程
存储其参数的副本,如果你想传递引用,你必须将它们包装在引用包装器
中。请参阅相关问题的答案。
future<typename result_of<Fn(Args&&...)>::type>
^^^^^^^^^ ^^^^^^