访问模板父类的静态成员

时间:2015-05-14 19:31:38

标签: 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;
}

这段代码会产生错误

  

错误:使用未声明的标识符'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;
}

为什么子模板类不能隐式推断出继承成员的适当范围?

1 个答案:

答案 0 :(得分:1)

编译器不解析模板基类的继承成员,因为您可能具有未定义成员的特化,并且在这种情况下整个解析/名称解析业务将变得非常困难。

如果您的会员是非静态会员,那么使用this->n_parent&#34;确保&#34; n_parent确实是基类成员的编译器。如果成员是static,则没有this指针(如您所述),因此唯一的选择是像您一样限定基类。

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

相关问题