std::异步与非静态成员函数

std::async with non static member functions

本文关键字:静态成员 函数 异步 std      更新时间:2023-10-16

我正在尝试异步评估代码的一部分

#include <stdio.h>
#include <string>
#include <memory>
#include <future>
#include <map>
namespace IG
{
typedef std::map<uint, std::string> CadDef;
class FooFoo
{
CadDef foo()
{
CadDef cdef{};
cdef[1] = "aa";
return cdef;
}
};
}
int main()
{
auto ptr = std::make_unique<IG::FooFoo>();
std::future<IG::CadDef> resFut = std::async(ptr->foo);
auto res = resFut.get();
return 0;
}

但是代码无法编译 - (在海湾合作委员会(

error: invalid use of non-static member function ‘IG::CadDef IG::FooFoo::foo()’

(在 msvc 上 - 我的主要程序,从中我抽象出最小示例(

error C3867: 'IG::FooFoo::foo': non-standard syntax; use '&' to create a pointer to member
error C2672: 'std::async': no matching overloaded function found
error C2780: 'std::future<_Invoke_traits<void,decay<_Ty>::type,decay<_ArgTypes>::type...>::type> std::async(std::launch,_Fty &&,_ArgTypes &&...)': expects 3 arguments - 1 provided

似乎MSVC在抱怨我没有使用ptr->foo()但我不确定。

我做错了什么?

您可以使用 lambda,如下所示,使用策略*

auto handle = std::async(std::launch::async, [&ptr](){
return ptr->foo(); // Ofcourse make foo public in your snippet
});

auto res = handle.get();

*不一定是必需的

异步将函数地址作为参数,但它该函数是一个类成员函数,您必须将其绑定到可以调用此函数的对象。

所有函数(包括方法(都移动到二进制文件的代码。 这就是为什么sizeof(T( 等于所有类数据成员(包括虚拟表指针 (vptr( 如果存在(的大小之和。

class A {void method() };可以表示为void method(A* a) {}

知道所有这些信息,你应该bind对象的方法

int main()
{
auto ptr = std::make_unique<IG::FooFoo>();
std::future<IG::CadDef> resFut = std::async(&IG::FooFoo::foo, ptr.get());
auto res = resFut.get();
return 0;
}