c++ - std::async过多参数

标签 c++ asynchronous arguments future

好的,所以我试图在项目中使用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();
}

关于c++ - std::async过多参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60748857/

相关文章:

.net - 带参数的 RelayCommand 抛出 MethodAccessException

c++ - 如何将事件监听器/信号添加到简单的超人类?

r - 如何将符号放入参数列表

c++ - 如何跨文件使用单个命名空间?

c++ - boost::deadline_timer::async_wait 不是异步的

javascript - Ajax(以前称为 AJAX)和 AJANE 之间的实际区别是什么?

javascript - Mongoose Async 查找所有内容并更新每个内容

bash - 使用不带参数的 getopts 获取帮助输出

c++ - 以低权限枚举 Windows 上的共享文件夹

c++ - 如何将数据从资源指针存储到 C++ 中的静态内存缓冲区?