模板继承和成员访问 [英] template inheritance and member access

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

问题描述

我有以下简单代码:

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

template< typename T>
struct derived:base< T>
{
void print()
{
使用base< T> :: x; // error:base< T>不是命名空间
std :: cout<< x<< std :: endl;
}
};



当我编译代码时(使用GCC-4.7.2),我得到你看到的错误



我在这里阅读: http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Name-lookup.html#Name-lookup
表示

 使用base< T> :: x 


才能引入基类的范围。任何想法有什么问题?提前感谢!

解决方案

在类中使用声明而不是在函数体中:

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

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

(当然是负责确保实际上 std :: vector 重载code>,例如使用 pretty打印机。)


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!

解决方案

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.)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆