在类模板的成员函数的实例化中,非静态成员函数的使用无效

Invalid use of non-static member function In instantiation of member function of a class template?

本文关键字:函数 静态成员 无效 实例化 成员      更新时间:2023-10-16

我想要一个类模板来启动一些线程来测试一些函数,这些函数访问一些共享状态。

#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);
}

这会产生以下错误。为什么以及如何修复?

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(

编辑:

按照@Igor的建议,它在更改为std::thread( &A::foo, this, i, n )后进行编译。据我所知,函数名在传递到函数时会衰减为指针。为什么我们仍然需要"与"answers"&"?

Re:为什么需要"与"符号。因为标准是这么说的。

[expr.prim.general]/13只能使用表示类的非静态数据成员或非静态成员函数的id表达式

(13.1)-作为类成员访问(5.2.5)的一部分,其中对象表达式引用成员的类或从该类派生的类,或

(13.2)-形成指向成员(5.3.1)或的指针

(13.3)--如果id表达式表示非静态数据成员,并且它出现在未赋值的操作数中。

此外:

[expr.ref]/4…以下规则之一适用。

(4.3.2)--否则,如果E1.E2指非静态成员作用[t] 表达式只能用作左侧操作数成员函数调用(9.3)…

因此,基本上,A::foo只能合法地出现在前面的与号("形成指向成员的指针")或后面的开头paren("函数调用的左侧操作数")。