2

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?

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51
Tika Gurung
  • 135
  • 1
  • 4
  • 1
    Why does `typename` inside a loop make any sense? What are you doing with `itr` here other than declaring it? This code needs a bit more context to make sense. – tadman Jul 06 '17 at 09:21
  • This question is exercise from my book.I think this explanation from my book will clarify: – Tika Gurung Jul 06 '17 at 09:24

0 Answers0