使用模板类进行继承

Inheritance with template classes

本文关键字:继承      更新时间:2024-09-27

我试图弄清楚,如何从一个模板类继承到另一个模板类。问题是:我不能使用父类的受保护成员。

例:

template <class N>
class Parent {
protected:
N member;
public:
Parent(N aa){
member = aa;
}
};

class Child1: public Parent<int>{
public:
Child1(int a): Parent<int>(a) {
member += 1; // works
}
};
template<class Q>
class Child2: public Parent<Q>{
public:
Child2(int a): Parent<Q>(a) {
member += 1; // does not work (use of undeclared identifier)
}
};

如何在 Child2 类中使用"成员"?

感谢您抽出宝贵时间

您需要使用this->memberParent<Q>::member

在第二种情况下,member是"依赖名称",因为基类模板Parent<Q>member的存在取决于模板中class Q的类型,而在第一个示例中没有依赖类型,编译器可以静态分析Parent<int>包含member