STL compilation error when defining an iterator in a template class

The code below gives an 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 be right?

+5
source share
2 answers

You need to typename std::list<T>::iterator. This is due to the fact that it listdepends on the template parameter, so the compiler cannot know what exactly will be indicated in it iterator(well, technically it would be possible to know, but the C ++ standard does not work that way). The keyword typenametells the compiler that the next one follows the type name.

+7
source

You need a type name

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

    private:
        std::list<T> elements;
};
+3
source

All Articles