C++ template typename iterator

CodeKingPlusPlus picture CodeKingPlusPlus · Jun 30, 2012 · Viewed 70.8k times · Source

Consider the following header file:

template <typename T> struct tNode
{
    T Data;                      //the data contained within this node
    list<tNode<T>*> SubNodes;       //a list of tNodes pointers under this tNode

    tNode(const T& theData)
    //PRE:  theData is initialized
    //POST: this->data == theData and this->SubNodes have an initial capacity
    //      equal to INIT_CAPACITY, it is set to the head of SubNodes
    {
        this->Data = theData;
        SubNodes(INIT_CAPACITY);   //INIT_CAPACITY is 10
    }

};

Now consider a line of code from another file:

list<tNode<T>*>::iterator it();  //iterate through the SubNodes

The compiler is giving me this error message: Tree.h:38:17: error: need ‘typename’ before ‘std::list<tNode<T>*>::iterator’ because ‘std::list<tNode<T>*>’ is a dependent scope

I have no idea why the compiler is yelling at me for this.

Answer

akappa picture akappa · Jun 30, 2012

In list<tNode<T>*>::iterator, you have a dependant name, that is, a name that depends on a template parameter.

As such, the compiler can't inspect list<tNode<T>*> (it doesn't have its definition at this point) and so it doesn't know whether list<tNode<T>*>::iterator is either a static field or a type.

In such a situation, the compiler assumes that it is a field, so in your case it yields a syntax error. To solve the issue, just tell the compiler that it is a type by putting a typename ahead of the declaration:

typename list<tNode<T>*>::iterator it