3

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 '&'?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Clinton
  • 57
  • 1
  • 4

1 Answers1

2

Re: why the ampersand is required. Because the standard says so.

[expr.prim.general]/13 An id-expression that denotes a non-static data member or non-static member function of a class can only be used:

(13.1) — as part of a class member access (5.2.5) in which the object expression refers to the member's class or a class derived from that class, or

(13.2) — to form a pointer to member (5.3.1), or

(13.3) — if that id-expression denotes a non-static data member and it appears in an unevaluated operand.

And further:

[expr.ref]/4 ...one of the following rules applies.

(4.3.2) — Otherwise, if E1.E2 refers to a non-static member function... [t]he expression can be used only as the left-hand operand of a member function call (9.3)...

So basically, A::foo can legally appear only with the ampersand in front ("to form a pointer to member") or with the opening paren following ("left-hand operand of a function call").

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85