Jean
Jean

Reputation: 83

STL compilation error when defining iterator within template class

The code below gives the error:

error: type ‘std::list<T,std::allocator<_Tp1> >’ is not derived from type ‘Foo<T>’
error: expected ‘;’ before ‘iter’

#include <list>

template <class T> class Foo 
{
  public:
      std::list<T>::iterator iter;

  private:
      std::list<T> elements;
};

Why and what should this be to be correct?

Upvotes: 4

Views: 891

Answers (2)

kennytm
kennytm

Reputation: 523184

You need a typename

template <class T> class Foo  {
    public:
        typename std::list<T>::iterator iter;

    private:
        std::list<T> elements;
};

Upvotes: 3

Tronic
Tronic

Reputation: 10430

You need typename std::list<T>::iterator. This is because list depends on the template parameter, so the compiler cannot know what exactly is the name iterator within it going to be (well, technically it could know, but the C++ standard doesn't work that way). The keyword typename tells the compiler that what follows is a name of a type.

Upvotes: 6

Related Questions