The scenario: I am trying to use three threads to execute a non static member function of objects contained within another object. The code does not compile, I get the error "Call to non-static member function without an object argument", even though I pass a pointer to each object. I also tried using std::ref().
#include <iostream>
#include <thread>
#include <vector>
class B {
public:
int val;
B(int i) : val(i) {};
void show_val() {
std::cout << val << std::endl;
}
};
class A {
public:
std::vector<B> bs;
void add_b(int i) {
bs.push_back(B(i));
}
void do_someting() {
{
thread t1(B::show_val(), &(a.bs[0]));
thread t2(B::show_val(), &(a.bs[1]));
thread t3(B::show_val(), &(a.bs[2]));
t1.join();
t2.join();
t3.join();
}
}
};
int main() {
A a;
a.add_b(1);
a.add_b(2);
a.add_b(3);
a.do_someting();
return 0;
}
I can't find much on this specific problem. Usually this kind of code works for me when I call from within the class B itself and pass this pointer to the thread constructor.