访问模板父类的静态成员

access static member of template parent class

本文关键字:静态成员 父类 访问      更新时间:2023-10-16
#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指针(如您所提到的),因此唯一的选择是像您那样限定基类。

相关:派生模板类访问基类member-data