C++ typename

Typename is a keyword used in C++ to resolve ambiguity. Consider the following two classes:

class IteratorIsType {
    class iterator {
        int it;
class IteratorIsMember {
    static int iterator;

Ok, now I imagine a templated function like this:

template <class T>
void Foo(){

What does T::iterator inside Foo refers to? If we call Foo<IteratorIsType>, then T::iterator refers to the nested class type defined inside IteratorIsType class. Otherwise, if we call Foo<IteratorIsMember>, T::iterator refers to the static variable named iterator (note that the qualifier name T:: is necessary since ‘iterator’ is static). We then have an ambiguity.

C++ compilers are told to resolve ambiguity considering T::iterator as a variable name, not a type. If one wants the second option, we must include the keyword typename before.

Completing the function we have:

template <class T>
void function(){
    int a = T::iterator; // sees T::iterator as a member of class T
    typename T::iterator it; // sees T::iterator as a nested type of class T

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s