好,所以我试图在项目中使用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
假定其参数列表中的指向成员函数的指针之后将是对该成员函数应应用到的对象的指针或引用。