I want a class template to start some number of threads to test some functions, which access some shared states.
#include <vector>
#include <thread>
using namespace std;
template<std::size_t M, std::size_t N>
class A {
public:
void test(std::size_t n) {
std::vector<std::thread> ts;
for(int i = 0; i < N; ++i){
ts.push_back(
std::thread( A::foo, this, i, n )
);
}
for(auto& thread : ts){
thread.join();
}
}
private:
void foo( std::size_t tid, std::size_t n ) {
}
};
int main() {
A<10, 2> tester;
tester.test(1000);
}
This gives following error. Why and how to fix?
prog.cpp: In instantiation of 'void A<M, N>::test(std::size_t) [with unsigned int M = 10u; unsigned int N = 2u; std::size_t = unsigned int]':
prog.cpp:27:18: required from here
prog.cpp:11:27: error: invalid use of non-static member function
threads.push_back(
Edit:
It compiles after changing to std::thread( &A::foo, this, i, n )
as @Igor suggested. As far as I understand, function name decay to a pointer when passing into a function. Why do we still need the ampersand '&'?