C++ list <T> :: iterator无法在派生类模板中使用

Rom*_*udl 5 c++ inheritance templates iterator g++

g ++编译器给出了这个错误:expect`;' 在'它'之前

template <typename T>
class myList : public std::list<T>
{   
public:

  void foo () 
  { 
    std::list<T>::iterator it;       // compiler error as above mentioned, why ???
  }
};
Run Code Online (Sandbox Code Playgroud)

谢谢.

小智 15

用g ++.无论何时在模板中,您都会看到错误:

error: expected ';' before 'it'
Run Code Online (Sandbox Code Playgroud)

怀疑你需要一个类型名称:

typename std::list<T>::iterator it;  
Run Code Online (Sandbox Code Playgroud)

在模板中,您需要声明一个新类型(在本例中为列表迭代器),这取决于一个或多个模板参数.这种需求并不是g ++ BTW独有的,它是标准C++的一部分.


GMa*_*ckG 10

尼尔给了你答案.也就是说,你可能想要制作一些typedef并使用它们,所以你的工作不会变得那么乏味(并且它增加了可读性):

template <typename T>
class myList : public std::list<T>
{   
public:
    typedef T value_type;
    typedef const T const_value_type;
    typedef value_type& reference;
    typedef const_value_type& const_reference;
    typedef value_type* pointer;
    typedef const_value_type* const_pointer;

    typedef std::list<T> base_container;
    typedef typename base_container::iterator iterator;
    typedef typename base_container::const_iterator const_iterator;

    void foo () 
    { 
        iterator it; // easy peasy
    }
};
Run Code Online (Sandbox Code Playgroud)

使用typedef是很自由的.

此外,从标准容器继承可能是一个坏主意,因为它们并不是真的用于这样的事情.例如,如果您正在寻找容器的某些扩展,则自由功能通常是最佳选择.