0

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!

Edited by myk45: n/a

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by myk45
0

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 .

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.