Connecting Tech Pros Worldwide Forums | Help | Site Map

Usage of typename

Dilip
Guest
 
Posts: n/a
#1: Sep 23 '06

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?


Julián Albo
Guest
 
Posts: n/a
#2: Sep 23 '06

re: Usage of typename


Dilip wrote:
Quote:
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.

--
Salu2
Jakob Bieling
Guest
 
Posts: n/a
#3: Sep 23 '06

re: Usage of typename


Dilip <rdilipk@lycos.comwrote:
Quote:
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
--
jb

(reply address in rot13, unscramble first)


Closed Thread