c++ - 使用用户定义的参数调用未来/异步并调用类方法
问题描述
是否可以异步调用函数并使用类方法返回值:
void A::GetReply()
{
auto fn = std::async([this](const struct mydata& msg)
{
oncall(msg);
});
}
int A::onReply(const struct mydata& msg)
{
return msg.value;
}
我得到编译错误:
6>: error C2672: 'std::async': no matching overloaded function found
6>: error C2893: Failed to specialize function template 'std::future<_Invoke_traits<void,_Callable,decay<_ArgTypes>::type...>::type> std::async(_Fty &&,_ArgTypes &&...)'
6> with
6> [
6> _Callable=decay<_Ty>::type
6> ]
6>: note: With the following template arguments:
6>: note: '_Fty=A::{ctor}::<lambda_75cbb6e549dc12613fd9546c1d31aa61>'
6>: note: '_ArgTypes={}'
6>: error C2780: 'std::future<_Invoke_traits<void,_Callable,decay<_ArgTypes>::type...>::type> std::async(std::launch,_Fty &&,_ArgTypes &&...)': expects 3 arguments - 1 provided
6> with
6> [
6> _Callable=decay<_Ty>::type
6> ]
6>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.15.26726\include\future(1821): note: see declaration of 'std::async'
什么是实现“未来”函数调用的正确方法,启动为异步并获取异步函数调用的返回值?
解决方案
问题与
auto fn = std::async([this](const struct mydata& msg)
{
oncall(msg);
});
是 lambda 需要一个参数,但您没有将一个参数传递给async
. 您必须传递给async
要异步运行的函数及其所有参数。如果msg
是班级成员,那么您可以将签名更改为
auto fn = std::async([this]()
{
oncall(msg);
});
然后msg
是this->msg
。
推荐阅读
- python - 如何从包含字典列表的字典中获取项目
- javascript - Vue应用程序中的静音更新无限循环
- javascript - 如何使用http请求根据规则访问firebase实时数据库
- reactjs - React 路由器正在堆叠路由
- python - 根据索引填写数据
- javascript - 如何将单个对象迭代到定义格式内的多个对象的新数组中
- python - 我使用 Kivy UrlReguest 下载并显示 Json 文件,但在 android 上没有任何效果,为什么?
- c# - 检测 C# 表单外的鼠标点击
- node.js - 如何在 NestJS 和 Jest 中测试 .map() 函数
- python - 在python中将大文件(500MB +)编码为base64