C ++ template syntax error

My C ++ is a little rusty, working in Java and C # for the past year and a half. I have a silly little error that I just can't figure out.

I have shortened the code as much as possible.

#include <list>
template<class T> class Subscriber
{
    virtual void published( T t ) = 0;
};

template <class T> class PubSub
{
private:
    std::list< Subscriber<T>* > subscribers;
public:
    void publish( T t );
};

template<class T> void PubSub<T>::publish( T t ) 
{
    for( std::list< Subscriber<T>* >::iterator i = subscribers.begin(); i != subscribers.end(); ++i )
        i->published( t );
}

      

When I try to compile this (by including this header file in my code file) I get the following error:

../util/pubsub.h: In member function ‘void PubSub<T>::publish(T)’:
../util/pubsub.h:18: error: expected `;' before ‘i’
../util/pubsub.h:18: error: ‘i’ was not declared in this scope

      

What am I missing here?

+2


source to share


3 answers


for( typename std::list< Subscriber<T>* >::iterator i = ...
     ^^^^^^^^

      



+6


source


for( typename std::list< Subscriber<T>* >::iterator i = subscribers.begin(); i != subscribers.end(); ++i )

      



You need it typename

because it iterator

is a dependent name. The compiler must check the type of the template T

before it knows if it is a iterator

type or a value. In these cases, it is assumed to be the value unless you add typename

.

+6


source


it

std::list< Subscriber<T>* >::iterator

      

should be this

typename std::list< Subscriber<T>* >::iterator

      

The compiler assumes that nested names in templates are static variables (and not types) unless otherwise specified.

+4


source







All Articles