使用用户定义的参数调用future/async并调用类方法

Calling future / async with user defined parameter and invoking a class method

本文关键字:调用 future 类方法 async 参数 用户 定义      更新时间:2023-10-16

是否可以调用async函数并使用类方法返回值:

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 studio2017professionalvctoolsmsvc14.15.26726includefuture(1821): note: see declaration of 'std::async'

实现"future"的函数调用(以异步方式启动(并获取异步函数调用的返回值的正确方法是什么?

的问题

auto fn = std::async([this](const struct mydata& msg)
{
oncall(msg);
});

是lambda需要一个参数,但没有将其传递给async。您必须向async传递要异步运行的函数及其所有参数。如果msg是该类的成员,则可以将签名更改为

auto fn = std::async([this]()
{
oncall(msg);
});

则CCD_ 4为CCD_。