Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template syntax error

My C++ is a little rusty having worked in Java and C# for the last half dozen years. I've got a stupid little error that I just cannot figure out.

I've pared the code down 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 and compile this (by including this header file in a 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?

like image 829
Andrew Avatar asked Aug 29 '26 02:08

Andrew


2 Answers

for( typename std::list< Subscriber<T>* >::iterator i = ...
     ^^^^^^^^
like image 182
Marsh Ray Avatar answered Aug 30 '26 14:08

Marsh Ray


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

You need the typename because iterator is a dependent name. The compiler has to check the template type T before it knows whether iterator is a type or a value. In those cases, it assumes it to be a value, unless you add typename.

like image 45
jalf Avatar answered Aug 30 '26 16:08

jalf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!