类成员的继承,与模板混合

Inheritance of class members, mixed with templates

本文关键字:混合 成员 继承      更新时间:2023-10-16

在下面的代码中,为什么T2给出这个错误‘m_t’ was not declared in this scope,而TB是好的?

我如何在T2中访问T1的成员而仍然使用模板?

// All good
class TA
{
    public:
      TA() {}
    protected:
    int m_t;
};
class TB : public TA
{
    public:
      TB() {}
      int get()
      { return m_t; }
    protected:
};
// Error in T2
template<typename T>
class T1
{
    public:
      T1() {}
    protected:
    int m_t;
};
template<typename T>
class T2 : public T1<T>
{
    public:
      T2() {}
      int get()
      { return m_t; }
    protected:
};

您需要使用this->m_t使其成为依赖名称。编译模板时,分两个阶段查找名称。非依赖名称在编译器第一次解析模板时查找。依赖名称在模板实例化时查找。将其更改为this->m_t将延迟查找,直到get函数实际实例化之后,在这种情况下,基类类型已知,编译器可以验证成员的存在。