tags:

views:

84

answers:

2

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?

+5  A: 

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.

Tronic
I still don't get why this is so. For example, why don't we need to use 'typename std::list<T> elements'?
Vulcan Eager
@Agnel: Because then we won't be trying to access names defined within a template class.
UncleBens
+3  A: 

You need a typename

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

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