Using iterators inside templates

T

Tom McCallum

I have looked all afternoon and I can't find a definite answer on the
following problem. I have defined a class
My question is why can't I define my iterator below?

template<class T>
class myClass {
public:
void myfunction();
};

and then a function:

template<class T>
void myclass<T>::myfunction() {
multimap<double, T* > i; // why is this allowed and
multimap<double, T* >::iterator j; // why is this not allowed?
}

The error I get with the iterator line is "parse error before '=' token".

I read somewhere that you could not define partial iterators - but if you
cannot use them why bother being able to define containers in template
classes?

Any suggestions, workarounds, reasons would be greatly appreciated.

Many thanks

Tom
 
V

Victor Bazarov

Tom said:
I have looked all afternoon and I can't find a definite answer on the
following problem. I have defined a class
My question is why can't I define my iterator below?

template<class T>
class myClass {
public:
void myfunction();
};

and then a function:

template<class T>
void myclass<T>::myfunction() {
multimap<double, T* > i; // why is this allowed and
multimap<double, T* >::iterator j; // why is this not allowed?

Anything after '::' is a "dependent name". You have to tell the compiler
what you mean by using it.

Try

typename std::multimap<double,T*>::iterator j;

since you intend to use 'iterator' as a name of a type.
}

The error I get with the iterator line is "parse error before '=' token".

I read somewhere that you could not define partial iterators - but if
you cannot use them why bother being able to define containers in
template classes?

Any suggestions, workarounds, reasons would be greatly appreciated.

HTH

Victor
 
T

tom_usenet

I have looked all afternoon and I can't find a definite answer on the
following problem. I have defined a class
My question is why can't I define my iterator below?

template<class T>
class myClass {
public:
void myfunction();
};

and then a function:

template<class T>
void myclass<T>::myfunction() {
multimap<double, T* > i; // why is this allowed and
multimap<double, T* >::iterator j; // why is this not allowed?
}

In addition to Victor's comments, you may want to reconsider your use
of multimap<double, ...>, since this may assert:

typedef multimap<double, int> m_t;
m_t m;
m.insert(m_t::value_type(2.3, 0));
assert(m.count(2.3));

Don't forget that doubles are only approximate.

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top