开发者

C++ list<T>::iterator cant be used in derived class template

开发者 https://www.devze.com 2022-12-25 13:54 出处:网络
g++ compiler gives this error: expected `;\' before \'it\' template <typename T> class myList : public std::l开发者_JAVA百科ist<T>

g++ compiler gives this error: expected `;' before 'it'

template <typename T>
class myList : public std::l开发者_JAVA百科ist<T>
{   
public:

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

Thanks.


In g++. whenever in a template you see the error:

error: expected ';' before 'it'

suspect you need a typename:

typename std::list<T>::iterator it;  

This is needed when in a template you have a new type declared (in this case the list iterator) which is dependant on one or more of the template parameters. The need is not unique to g++ BTW, it's part of standard C++.


Neil's given you your answer. That said, you might want to make a slew of typedef's and use those, so your work doesn't become so tedious (and it increases readability):

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

It's quite common to be liberal with your use of typedef's.

Also, inheriting from a standard container might be a bad idea, since they aren't really made for such a thing. For example, a free function is often the best choice if you're looking for some extensions to a container.

0

精彩评论

暂无评论...
验证码 换一张
取 消