首页 > 解决方案 > 使用用户定义的参数调用未来/异步并调用类方法

问题描述

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

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'

什么是实现“未来”函数调用的正确方法,启动为异步并获取异步函数调用的返回值?

标签: c++c++11

解决方案


问题与

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

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

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

然后msgthis->msg


推荐阅读