std::async 参数过多

std::async too many arguments

好的,所以我正在尝试在项目中使用 std::future,但是我正在使用它的 std::async 一直告诉我参数太多。我试着看看我是否没有误解模板,但我没有发现任何错误......这是调用:

QVector<MyMesh::Point> N1;
QVector<MyMesh::Point> N2;
future<QVector<MyMesh::Point>> FN1 = async(launch::async, rangeSearch, &mesh, vit->idx(), diagBoundBox*0.02);
future<QVector<MyMesh::Point>> FN2 = async(launch::async, rangeSearch, &mesh, vit->idx(), diagBoundBox*0.02*2);
N1 = FN1.get();
N2 = FN2.get();

还使用了 rangeSearch 方法:

QVector<MyMesh::Point> rangeSearch(MyMesh *_mesh, int pid, float range);

有什么不妥吗?

编辑:这是一个最小的可重现示例,对第一个感到抱歉。

#include <future>

class Class
{
public:

    void A();
    int F(int a, int b, int c);
};

int Class::F(int a, int b, int c){
    return a+b+c;
}

void Class::A(){
    int N1;
    int N2;
    std::future<int> FN1 = std::async(std::launch::async, F, 1, 2, 3);
    std::future<int> FN2 = std::async(std::launch::async, F, 1, 2, 3);
    N1 = FN1.get();
    N2 = FN2.get();
}

int main()
{
    Class O;
    O.A();
}

还有错误:

main.cpp: In member function ‘void Class::A()’:
main.cpp:18:69: error: invalid use of non-static member function ‘int Class::F(int, int, int)’
     std::future<int> FN1 = std::async(std::launch::async, F, 1, 2, 3);
                                                                     ^
main.cpp:11:5: note: declared here
 int Class::F(int a, int b, int c){
     ^~~~~
main.cpp:19:69: error: invalid use of non-static member function ‘int Class::F(int, int, int)’
     std::future<int> FN2 = std::async(std::launch::async, F, 1, 2, 3);
                                                                     ^
main.cpp:11:5: note: declared here
 int Class::F(int a, int b, int c){
     ^~~~~

这里的问题不在于您传递的参数数量。它与参数的性质有关——具体来说,试图将成员函数直接传递给 std::async.

处理这个问题的最简单方法几乎肯定是通过 lambda 表达式调用成员函数:

#include <future>

class Class
{
public:
    void A();
    int F(int a, int b, int c);
};

int Class::F(int a, int b, int c)
{
    return a + b + c;
}

void Class::A()
{
    int N1;
    int N2;
    std::future<int> FN1 = std::async(std::launch::async, [&](int a, int b, int c) {
        return F(a, b, c); }, 1, 2, 3);
    std::future<int> FN2 = std::async(std::launch::async, [&](int a, int b, int c) {
        return F(a, b, c);}, 1, 2, 3);

    N1 = FN1.get();
    N2 = FN2.get();
}

int main()
{
    Class O;
    O.A();
}

代码中有两个问题。首先,要创建指向成员函数的指针,语法是 &Class::F。其次,当您使用指向成员函数的指针时,您需要一个对象来应用它。所以正确的调用(在成员函数Class::A内)是

std::future<int> FN1 =
    std::async(std::launch::async, &Class::F, this, 1, 2, 3);

std::async 假定其参数列表中指向成员函数的指针后跟指向成员函数应应用于的对象的指针或引用。