Inheritance of class members, mixed with templates

最后都变了- 提交于 2019-12-07 14:05:49

问题


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

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

回答1:


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.



来源:https://stackoverflow.com/questions/16420012/inheritance-of-class-members-mixed-with-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!