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

时间:2018-10-29 13:30:40

标签: c++ c++11

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

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'

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

1 个答案:

答案 0 :(得分:1)

问题

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

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

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

,然后msgthis->msg