Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL compilation error when defining iterator within template class

Tags:

c++

stl

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?

like image 491
Jean Avatar asked Feb 11 '10 07:02

Jean


2 Answers

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.

like image 148
Tronic Avatar answered Oct 15 '22 21:10

Tronic


You need a typename

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

    private:
        std::list<T> elements;
};
like image 22
kennytm Avatar answered Oct 15 '22 21:10

kennytm