Search code examples
c++templatestypename

C++ - Using typename and template error


I built a doubly linkedlist using a template class, The class i built contain innter public class linkedListNode which contain private field next and previous. For encapsulation issues i wanted to define a method that return the next node

template <class T>
MyLinkedList<T>::MyLinkedListNode* MyLinkedList<T>::MyLinkedListNode::getNext()
{
    return this -> next;
}

but it is a compilation error. I also tryed to use typename and it also a compilation error

The compliation error is :

need ‘typename’ before ‘MyLinkedList::MyLinkedListNode’ because ‘MyLinkedList’ is a dependent scope


Solution

  • When MyLinkedList<T> is instantiated, there's a chance that it could be a value instead of a type. The typename keyword is required to let the compiler know that it is a type. For a dependent name, the compiler does not make any assumptions. It is up to the programmer to sprinkle typename and template keywords in the correct locations. Lucky for you, it's right in the error message. It can't get any easier than that.