Usage of typename

D

Dilip

Folks

I understand that the keyword typename is also used to indicate that a
dependant parameter is a type. However I am a little unsure why I need
typename in this following example:

template<typename K, typename V>
class MyMap
{
public:
typedef typename std::map<K, V>::iterator MyMap_Iterator;
};

why is a typename needed here? what does iterator have to do with the
template parameters K and V? Irrespective of what K and V are am I not
trying to just typedef std::map's iterator? What am I missing?
 
?

=?ISO-8859-15?Q?Juli=E1n?= Albo

Dilip said:
public:
typedef typename std::map<K, V>::iterator MyMap_Iterator;
};

why is a typename needed here? what does iterator have to do with the
template parameters K and V? Irrespective of what K and V are am I not
trying to just typedef std::map's iterator? What am I missing?

std::map is a template, not a class, the class that can have a type called
iterator is map <K,V>. And that class is dependent of K and V. For example,
imagine than std::map has an specialization for some concrete K and V you
use, and that specialization has no member called iterator, or has one that
is not a type. May seem strange in the std::map concrete case, but the
rules are generic, it will be very confusing to have different rules for
standard library templates and other templates.
 
J

Jakob Bieling

Dilip said:
Folks

I understand that the keyword typename is also used to indicate that a
dependant parameter is a type. However I am a little unsure why I
need typename in this following example:

template<typename K, typename V>
class MyMap
{
public:
typedef typename std::map<K, V>::iterator MyMap_Iterator;
};

why is a typename needed here? what does iterator have to do with the
template parameters K and V? Irrespective of what K and V are am I
not trying to just typedef std::map's iterator? What am I missing?

Afaik, 'iterator' _could_ (just suppose you have not seen the class
definition, yet) also be a function or a static member variable. By
prepending 'typename' you tell the compiler, that 'iterator' really is a
type inside this specialization of the template, so it does not have to
look it up itself.

I am sure there is a more technical and more accurate explanation to
this, like a quote from the Standard. The above is what I use to
determine, if I need 'typename' or not. I got this explanation from this
newsgroup as well, btw. Try googling the groups for my name and
'typename' in the subject.

hth
 

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

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top