c++ - 访问模板父类的静态成员

标签 c++ templates inheritance static

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

这段代码会产生错误

error: use of undeclared identifier '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指针(正如您提到的),因此唯一的选择是像您一样限定基类。

相关:Derived template-class access to base-class member-data

关于c++ - 访问模板父类的静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30245777/

相关文章:

.net - 派生自 C++ 中的 .NET 抽象类,System::IO::TextWriter

html - 将文本元素的宽度继承到换行符 HTML

c++ - 建立数据库,读取方法

c++ - 即使提供了确切的参数,也会忽略显式复制构造函数

templates - 模板中的 for 循环

c++ - 从具有模板化构造函数的非模板化类继承 - 如何解决歧义?

python - 类型错误 : Error when calling the metaclass bases module

c++ - 我不明白 [dcl.enum]/4 与下面突出显示的 "enclosing enum specififer"相关的内容

c++ - 内核模块和 SCHED_RR 线程的优先级

c++ - 函数模板重载 - 偏特化