One of the motivations behind requiring C++ programmers to put the typename keyword before accessing a type nested inside a templatized type was to prevent ambiguity in templates. For example, consider the following code, which assumes the existence of a template type called MyTemplate:
template <typename T> void MyFunction(const T& elem)
{
int itr;
while(true)
{
typename MyTemplate<T>::Inner * itr;
}
}
Consider the line
typename MyTemplate<T>::Inner * itr.
Since we have the typename keyword here, the compiler understands that we're declaring a pointer of type MyTemplate::Inner* called itr. If we don't put the
typename
keyword in here, C++ will think that
MyTemplate<T>::Inner
is a class constant rather than a type. What will the statement
MyTemplate<T>::Inner * itr
mean in this case? Does the difference between these two cases help explain why the typename keyword is necessary?