模板继承和成员访问

lin*_*ver 1 c++ inheritance templates 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;
    }
};
Run Code Online (Sandbox Code Playgroud)

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

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

using base<T>::x
Run Code Online (Sandbox Code Playgroud)

必须包含以引入基类的范围.有什么想法有什么不对?先感谢您!

Ker*_* SB 7

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

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

    void print()
    {
        std::cout << x << std::endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

(当然,您有责任确保实际上存在operator<<过载std::vector,例如使用漂亮的打印机.)