本文介绍了继承类成员,与模板混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码,为什么T2给这个错误'm_t'没有声明在这个范围,而TB很好?

in the code below, why does T2 give this error ‘m_t’ was not declared in this scope, while TB is fine ?

如何在T2中访问T1的成员,同时仍然使用模板?

And how can I have access to T1's members in T2 while still using templates ?

// 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:
};


推荐答案

您需要使用 - > m_t ,使其成为依赖名称。当编译模板时,将在两个阶段中查找名称。当编译器首次解析模板时,将查找非依赖名称。在模板被实例化时查找从属名称。将其更改为 this-> m_t 延迟查找,直到 get 函数实际被实例化,基类类型是已知的,编译器可以验证成员的存在。

You need to use this->m_t to make it a dependent name. When templates are compiled, names are looked up in two stages. Non-dependent names are looked up when the compiler first parses the template. Dependent names are looked up when the template is instantiated. Changing it to this->m_t delays look-up until after the get function is actually instantiated, in which case the base class type is known and the compiler can verify the member's existence.

这篇关于继承类成员,与模板混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:43