从类函数内部调用的线程向量



我正在尝试做一些类似于中最后一段代码的事情

然而,在代码中您可以看到vec_thr.emplace_back(&Test::testme, std::move(t1), std::cref(str));是在主函数内部调用的。

我想通过对象Test的成员函数来实现这一点。

所以我做了

#include <thread>
#include <string>
#include <vector>
#include <iostream>
class Test
{
private:
public:
void testme(const std::string& _str)
{
std::cout << "Hello " + _str << std::endl;
}
void testFurther(const std::string& _str){

std::vector<std::thread> vec_thr;
// pass the constructor parameters you would have passed to std::thread
// to the emplace_back() function - they are forwarded to the thread that
// is constructed "in place" inside the vector
for(int i=0;i<2;i++){
//HERE I am trying how to write this correctly trying the following:
//           vec_thr.emplace_back(&Test::testme, std::move(t1), std::cref(str));
vec_thr.emplace_back(testme, std::move(this), std::cref(_str));
//             vec_thr.emplace_back(testme, std::cref(_str));
}
// Don't forget to join all your threads to make sure
// they complete before moving on/exiting
for(auto& t: vec_thr)
t.join();

}
};
int main()
{
const std::string str = "there";
Test t1/*, t2*/;
t1.testFurther(str);
}

然而,它不起作用。我收到错误信息

error: invalid use of non-static member function

有办法做到这一点吗。我想做完全相同的事情,最初从主要功能

我似乎已经通过将类Test函数testMore更改为来解决问题

void testFurther(const std::string& _str){

std::vector<std::thread> vec_thr;
// pass the constructor parameters you would have passed to std::thread
// to the emplace_back() function - they are forwarded to the thread that
// is constructed "in place" inside the vector
for(int i=0;i<2;i++){
//           vec_thr.emplace_back(&Test::testme, std::move(t1), std::cref(str));
//             vec_thr.emplace_back(testme, std::move(this), std::cref(_str));
//               vec_thr.emplace_back(&testme, this, std::cref(_str)); // ISO forbid taking the address of an unqualified or parenthesized non-static member function

vec_thr.emplace_back(&Test::testme, this, std::cref(_str)); //THIS WORKS
//             vec_thr.emplace_back(testme, std::cref(_str));
}
// Don't forget to join all your threads to make sure
// they complete before moving on/exiting
for(auto& t: vec_thr)
t.join();

}

这样看来效果不错。我只是想知道为什么我必须使用&Test::testme,因为Test是类的名称,而不是对象实例的名称

最新更新