简体   繁体   English

模板继承和成员访问

[英]template inheritance and member access

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. 当我编译代码(使用GCC-4.7.2)时,收到上面注释中看到的错误。

I read here: http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Name-lookup.html#Name-lookup that 我在这里阅读: http : //gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Name-lookup.html#Name-lookup

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! 先感谢您!

Put the using declaration in the class definition, not in the function body: using声明放在类定义中,而不是在函数主体中:

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 .) (当然, 您有责任确保您的std::vector实际上存在operator<<重载,例如,使用漂亮的打印机 。)

You can also make it work if you explicitly say that x is a member: 如果您明确地说x是成员,则也可以使其工作:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM