首页 > 解决方案 > std::async 参数太多

问题描述

好的,所以我试图在项目中使用 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){
     ^~~~~

标签: c++asynchronousargumentsfuture

解决方案


这里的问题不在于您传递的参数数量。它与参数的性质有关 - 特别是尝试将成员函数直接传递给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();
}

推荐阅读