#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
指针(正如您提到的),因此唯一的选择是像您一样限定基类。
关于c++ - 访问模板父类的静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30245777/