访问模板父类的静态成员
access static member of template parent class
#include<iostream>
template<int n>
class Parent
{
public:
static const unsigned int n_parent = 5 + n;
};
template<int n>
class Son : public Parent<n>
{
public:
static void foo();
static const unsigned int n_son = 8 + n;
};
template<int n>
void Son<n>::foo()
{
std::cout << "n_parent = " << n_parent << std::endl;
std::cout << "n_son = " << n_son << std::endl;
}
这段代码将产生错误
错误:使用未声明的标识符'n_parent'
我必须明确地指定模板参数:
template<int n>
void Son<dim>::foo()
{
std::cout << "n_parent = " << Son<n>::n_parent << std::endl;
std::cout << "n_son = " << n_son << std::endl;
}
为什么子模板类不能隐式地推断继承成员的适当作用域?
编译器不解析模板基类的继承成员,因为您可能有没有定义成员的专门化,在这种情况下,整个解析/名称解析业务将变得相当困难。
如果成员是非静态的,那么使用this->n_parent
"保证"编译器n_parent
确实是基类的成员。如果成员是static
,则没有this
指针(如您所提到的),因此唯一的选择是像您那样限定基类。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 类的全局对象和静态成员
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 模板化类中静态成员的延迟初始化
- 使用静态成员声明类时遇到问题
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- decltype:使用指针访问类的静态成员
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 从模板化父类中的派生内部类访问受保护的成员变量
- 在 C++11 中轻松初始化模板类的静态成员,没有 clang 警告
- 从相同类型的静态成员进行类内初始化
- 具有静态成员的类的前向声明
- C 不能将带有父类指针作为类型的静态模板成员定义引用
- 具有静态成员的类包含C++中的静态成员
- 子类不是父类的静态成员
- 在包含其自身类型的静态成员的类中使用 __declspec(dllimport)
- 为什么静态成员的类内初始化会违反 ODR
- 命名空间中的函数重载(与具有静态成员的类相比)是个坏主意吗
- 访问模板父类的静态成员