gpt4 book ai didi

c++ - C++ 中类成员上的类和 std::async

转载 作者:IT老高 更新时间:2023-10-28 12:55:56 57 4
gpt4 key购买 nike

我正在尝试编写一个类成员,它可以并行多次调用另一个类成员。

我写了一个简单的问题示例,甚至无法编译它。我在调用 std::async 时做错了什么?我想问题在于我如何传递函数。

#include <vector>
#include <future>
using namespace std;
class A
{
int a,b;
public:
A(int i=1, int j=2){ a=i; b=j;}

std::pair<int,int> do_rand_stf(int x,int y)
{
std::pair<int,int> ret(x+a,y+b);
return ret;
}

void run()
{
std::vector<std::future<std::pair<int,int>>> ran;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
auto hand=async(launch::async,do_rand_stf,i,j);
ran.push_back(hand);
}
}
for(int i=0;i<ran.size();i++)
{
pair<int,int> ttt=ran[i].get();
cout << ttt.first << ttt.second << endl;
}
}
};

int main()
{
A a;
a.run();
}

编译:

g++ -std=c++11 -pthread main.cpp 

最佳答案

do_rand_stf是一个非静态成员函数,因此不能在没有类实例的情况下调用(隐式 this 参数。)幸运的是,std::async处理它的参数,如 std::bind , 和 bind反过来可以使用std::mem_fn将成员函数指针转换为接受显式 this 的仿函数参数,所以你需要做的就是传递thisstd::async传递 do_rand_stf 时调用并使用有效的成员函数指针语法:

auto hand=async(launch::async,&A::do_rand_stf,this,i,j);

不过,代码中还有其他问题。首先,您使用 std::coutstd::endl没有 #include学习 <iostream> .更严重的是,std::future不可复制,只能移动,所以不能push_back命名对象 hand不使用 std::move .或者,只需传递 async结果到push_back直接:

ran.push_back(async(launch::async,&A::do_rand_stf,this,i,j));

关于c++ - C++ 中类成员上的类和 std::async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11758414/

57 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com