0

I have linked list class that implements a node structure, like this:

template<class T>
class LinkedList
{
public:
    struct Node {
        T value;
        Node *next;
    };

    int Length;
    Node *head;
    Node *tail;

    LinkedList() {
    Length = 0;
    Node* head = nullptr;
    Node* tail = nullptr;
    }
};

I tried accessing the node Node structure from the driver file like so:

#include "LinkedList.h"

template<class T>
void foo(LinkedList<T> list) {
    LinkedList<T>::Node* a = list.head; // does not work
    LinkedList<int>::Node* b = list.head; // works (if T is int of course)
}

Using a template T does not work (it gives me "identifier not found" error message), while directly specifying the correct datatype works. Why is that? Is there a way to avoid the error?

Ach113
  • 1,775
  • 3
  • 18
  • 40
  • Write `typename LinkedList::Node *a`. Basically, since `LinkedList` names a template specialization, the compiler doesn't know that `LinkedList::Node` is type, because it could instead be a static variable, or maybe a member function, so you need to explicitly say that it is a type. See [the linked question](https://stackoverflow.com/q/610245/5684257) for why – HTNW Apr 26 '20 at 16:40
  • @HTNW, I actually saw that question, but did not understand how to use it for my problem. Thanks for the help – Ach113 Apr 26 '20 at 16:46

1 Answers1

1

Use typename LinkedList<T>::Node* a = ...

The problem is that not knowing what exactly T is, the compiler can’t be sure LinkedList<T>::Node is indeed a type (LinkedList could be specialized for T so the definition doesn’t help). You need to instruct it to treat it that way.

numzero
  • 2,009
  • 6
  • 6