C++ - Using typename and template error

192 Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

As the compiler tells you:

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

You should use typename because MyLinkedList<T>::MyLinkedListNode* is a dependent name (it depends on the template argument T). You can fix your code with:

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

As you can see it works just fine.

0
On

your compiler tell you the solution:

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