template inheritance and member access

╄→гoц情女王★ 提交于 2020-01-06 02:14:58

问题


I have the following simple code:

template <typename T>
struct base
{
  std::vector<T> x;
};

template <typename T>
struct derived : base<T>
{
  void print()
    {
      using base<T>::x;     // error: base<T> is not a namespace
      std::cout << x << std::endl;
    }
};

When I compile the code (using GCC-4.7.2) I get the error that you see in the comment above.

I read here: http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Name-lookup.html#Name-lookup that

using base<T>::x

has to be included in order to bring in the scope of the base class. Any ideas what is wrong? Thank you in advance!


回答1:


Put the using declaration in the class definition, not in the function body:

template <typename T>
struct derived : base<T>
{
    using base<T>::x;     // !!

    void print()
    {
        std::cout << x << std::endl;
    }
};

(Of course it's your responsibility to make sure that there's actually an operator<< overload for your std::vector, for example by using the pretty printer.)




回答2:


You can also make it work if you explicitly say that x is a member:

template <typename T>
struct base
{
  std::vector<T> x;
  base() : x(1) {}
};

template <typename T>
struct derived : base<T>
{
  void print()
    {
      std::cout << this->x[0] << std::endl;
    }
};

int main()
{
    derived<int> d;
    d.print();
}


来源:https://stackoverflow.com/questions/13252192/template-inheritance-and-member-access

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