C++ class template help.

Started by
4 comments, last by visitor 15 years, 4 months ago
I don't understand why it doesn't work. I can't create the iterator for a particular nested template declaration. Here goes. template<typename T> void GraphNode<T>::doSomething() { list< GraphNode<T>* > data; // works fine data.push_back(new GraphNode<T>()); // works fine too list< GraphNode<T>* >::iterator iter; // Doesn't work and I don't get it! // error message was // error: expected `;' before "iter" } What was it that I do wrongly? Please help. Regards.
Advertisement
try
typename list< GraphNode<T>* >::iterator iter;
Quote:Original post by SiCrane
try
typename list< GraphNode<T>* >::iterator iter;


Thanks now it works. This is not a commonly used syntax for declaring iterators, is it?
I rarely see it in examples.
What does it really do, by putting typename in front if the statement?
Are there other usage examples like that as well?

Thanks again.
Quote:Original post by Zerox Millienium
Quote:Original post by SiCrane
try
typename list< GraphNode<T>* >::iterator iter;


Thanks now it works. This is not a commonly used syntax for declaring iterators, is it?
I rarely see it in examples.
What does it really do, by putting typename in front if the statement?
Are there other usage examples like that as well?

Thanks again.


Only common in templates. The typename keyword tells the compiler that what follows is a type, as opposed to a static member or function or something. Somehow it's hard for the compiler to figure out what's a type and what's not in a template.
The typename keyword is used to specify that a qualified identifier of a dependent type is a type. A dependent type is a type the some depends on the type parameters of your template. Since list<GraphNode<T> *> uses T, it's a dependent type. list<GraphNode<T> *>::iterator is then a qualified identifier of a dependent type, so requires the typename keyword. If you had list<GraphNode<int> *>::iterator, it wouldn't require the typename keyword since it no longer depends on T. Similarly, list<GraphNode<T> *> by itself doesn't require the typename keyword since it's not a qualified identifier.
Quote:
Somehow it's hard for the compiler to figure out what's a type and what's not in a template.


Or they wanted to avoid the situation where the same code could produce a completely different meaning depending on what types it is instantiated with. Type A has x as a type, type B has x as a static member. Should the template compile for A and B alike, provided that otherwise there's no syntax error. (Although perhaps a lot of issues with dependent and non-dependent names are caused by the implementation difficulties...)

This topic is closed to new replies.

Advertisement