如何在传递异步时传递函数中的多个参数

如何在传递异步时传递函数中的多个参数

问题描述:

我希望传递函数的两个参数,该函数将两个参数作为参数传递给异步函数。我从来没有使用异步以往,所以我不知道如何做到这一点如何在传递异步时传递函数中的多个参数

因此,这是功能

double NearestPoints::otherCoordinate(Coordinate coordinate1, Coordinate** secondCoordinate){ 

这是异步函数

std::future<double> ret = std::async(&otherCoordinate,coordinate1,ref(coordinate2)); 

我敢肯定我我错误地实现了这个功能,但我只是想知道正确的实现。

在此先感谢!

这是你在找什么?

#include <iostream>  
#include <future>  


int add(int x,int y) {  
    return x+y; 
} 

int main() 
{ 
    std::future<int> fut = std::async(add, 10,20); 
    int ret = fut.get(); 
    std::cout << ret << std::endl;  
    return 0; 
} 
+0

注意'otherCoordinate'是一个成员函数。 NearestPoints的一个实例也需要被传入。 – phantom

+0

我不主要调用async。我在另一个函数的for循环中调用它,并且该函数也是NearestPoints的成员函数 –

从我可以告诉从你的问题看起来你已经忘记了将NearestPoints实例传递给你的std::async电话。由于NearestPoints::otherCoordinate是一个成员函数,因此需要为其this指针传递的NearestPoints类的实例。

要解决此问题,您应该传入当前实例的副本,以便该函数可以访问要在其上进行操作的实例。

您对std::async固定电话应该是这样的:

std::future<double> ret = std::async(&NearestPoints::otherCoordinate, *this, coordinate1, std::ref(coordinate2)); 
+0

当我尝试它给了我这个错误:'&':绑定成员函数表达式上的非法操作 –

+0

我的不好,你需要即使您的函数在类作用域内,也要将类名称放在成员函数名称的前面。固定。 – phantom

+0

现在它给了这两个错误。错误1:未能专门化功能模板'未知类型std :: invoke(_Callable &&,_ Types && ...)'\t NearestPoints。错误2:'初始化':无法从'std :: future '转换为'std :: future '\t NearestPoints –

解决电话如下:

std::future<double> ret = std::async(&NearestPoints::otherCoordinate,&instance_name,coordinate1,std::ref(coordinate2));