C++:与packaged_task异步构建
c++: Building async with packaged_task
我正在尝试与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
中就会缺少一个typename
,A
。
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 使用"Task"函数指针队列定义作业管理器
- 如何在C++中实现带有packaged_task的异步等待循环?
- Visual Studio C++ Project File CustomBuild Task: Filter Outp
- 创建 Spdlog 异步文件记录器时遇到困难
- C ++异步键盘输入(标准方式)
- 在 gtkmm 中异步加载图像
- 带有 Boost.Beast 的异步读取标头
- 如何在 c++ 中异步调用静态方法?
- libcurl :C++处理多个异步请求
- 如何在C++上启动异步线程
- TCP 服务器的异步读取使用 boost::asio 打印客户端套接字发送的数据
- 增强 ASIO 和串行端口异步读取
- 使用 Qt5 SQL 进行异步数据库访问的策略
- 如何使用从处理程序调度的最终回调将响应异步返回给调用方on_read?
- C++中真正的异步文件 IO
- 提升::Asio 异步聊天客户端停止与服务器通信
- 在 c++ 托管和异步运行中调用 c# 可执行文件
- std::异步与非静态成员函数