Search code examples
c++templatestypename

Why is typename necessary in return type? C++


Given a template class Queue with a nested Node struct.

Why is typename needed in the return type here?

template<typename T>
typename Queue<T>::Node* Queue<T>::test() {}

The nested struct Node in the template class Queue would be in the scope of Queue<T>:: without typename.

According to Where and why do I have to put the "template" and "typename" keywords?:

We decide how the compiler should parse this. If t::x is a dependent name, then we need to prefix it by typename to tell the compiler to parse it in a certain way.

But I don't see why it justifies using typename?


Solution

  • While parsing the return type (as defined in the question) we are not in the scope of Queue<T> yet. Your reasoning would be correct if you were to write

    template<typename T>
    auto Queue<T>::test() -> Node* {
    
    }
    

    The nested name qualifier of the fully qualified function name puts us into the scope of the current template specialization. Here unqualified name lookup finds Node* in the current specialization, where it is known to refer to a type.

    But while parsing the return type in your question the compiler hasn't yet encountered the "current specialization" where Node* can be unambiguously assumed to name a type. All it sees is us writing a dependent name from some specialization. As such, typename is required. It's no different to us having to write

    template<typename T>
    typename OtherUnrelatedClass<T>::Node* Queue<T>::test() {
    
    }