模板继承和成员访问

时间:2012-11-06 13:35:56

标签: c++ templates inheritance scope

我有以下简单的代码:

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

当我编译代码时(使用GCC-4.7.2),我得到你在上面评论中看到的错误。

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

using base<T>::x
必须包含

才能引入基类的范围。有什么想法有什么不对?提前谢谢!

2 个答案:

答案 0 :(得分:7)

using声明放在类定义中,而不是放在函数体中:

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

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

(当然 >确保operator<<实际上std::vector超载,例如使用pretty printer 。< / p>

答案 1 :(得分:4)

如果您明确说明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();
}