带有继承/模板问题的c++模板

The C++ template with inheritance/template issue

本文关键字:问题 c++ 模板 继承      更新时间:2023-10-16

我在一些项目中坚持使用以下代码(这是简化)。

template <class X >
class A {
  public:
    int a;
};
class Y;
class B : public A<Y> {
  void foo() {a = 0;}
};
template < class D >
class C : public A<D> {
  void foo() {a = 0;}
};

编译失败:

test.cpp:14:14: error: ‘a’ was not declared in this scope

为什么在C::foo中编译器不能识别A:: A而在B::foo中不能?谢谢。

aB中的依赖基类成员,您需要通过this->a访问它。