Hello everyone,

I came across the following in a book:

Keyword typename

The keyword typename was introduced to specify that the identifier that follows is a type.

Consider the following example:

template <class T>
Class MyClass {
typename T:: SubType * ptr;
...
};

Here, typename is used to clarify that SubType is a type of class T. Thus, ptr is a pointer to the type T:: SubType. Without typename, SubType would be considered a static member.

Can anyone please explain this? I didn't understand what the author meant by
"Thus, ptr is a pointer to the type T:: SubType" ?

Thanks!

Let's use a more complete example:

class Foo {
public:
    typedef int SubType;
};

template <class T>
class MyClass {
    typename T::SubType * ptr;
};

int main()
{
    MyClass<Foo> obj;
}

Foo::SubType is clearly a type, right? But in a dependent name context C++ will assume that the dependent name designates an object unless you qualify it with the typename keyword. A dependent name is a name that depends on a template argument (odd that, huh?), and won't be resolved until the template is instantiated. T::SubType is a dependent name because the parent class represented by template parameter T needs to be instantiated before SubType can be successfully resolved. In other words, T::SubType depends on the instantiation of T .

The end result is that MyClass<Foo>::ptr is a pointer to int because T::SubType resolves to Foo::SubType , which is a typedef for int .

Thanks Narue!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.