在类模板的成员函数的实例化中,非静态成员函数的使用无效
Invalid use of non-static member function In instantiation of member function of a class template?
我想要一个类模板来启动一些线程来测试一些函数,这些函数访问一些共享状态。
#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("函数调用的左侧操作数")。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 非静态成员函数的 decltype 格式不正确吗?
- 为什么 std::sort 找不到合适的(静态成员)函数重载?
- std::异步与非静态成员函数
- C++无效使用非静态成员函数?
- 指向重载静态成员的函数指针 - 在unique_ptr中用作自定义删除器
- 未使用的C++未优化的静态成员函数/变量
- C++:如何返回指向非静态成员函数的指针?
- 有没有一种方法可以使全局函数/静态成员函数一次可呼出
- 函数静态成员变量
- 隐藏模板化的辅助函数——静态成员或未命名的命名空间