8

I am attempting to templatize a few classes (LinkedListNode and LinkedList), such that

template <class T>
class LinkedListNode{
    public:
        T data;
        LinkedListNode *next;
        LinkedListNode();
};

In my LinkedList Class, I have private variables:

private:
    LinkedListNode *head;
    //iterator for traversing the list
    LinkedListNode *current;

};

When compiling, I am getting strange errors:

./LinkedList.h:38:3: error: unknown type name 'LinkedListNode'; did you mean 'LinkedList'? LinkedListNode *head; ^~~~~~~~~~~~~~ LinkedList ./LinkedList.h:13:7: note: 'LinkedList' declared here class LinkedList{ ^ ./LinkedList.h:40:3: error: unknown type name 'LinkedListNode'; did you mean 'LinkedList'? LinkedListNode *current; ^~~~~~~~~~~~~~ LinkedList ./LinkedList.h:13:7: note: 'LinkedList' declared here class LinkedList{ ^ LinkedList.cpp:7:1: error: 'LinkedListNode' is not a class, namespace, or enumeration LinkedListNode::LinkedListNode(){ ^ ./LinkedList.h:5:7: note: 'LinkedListNode' declared here class LinkedListNode{ ^

Why am i getting these errors if it says my LinkedListNode is also being declared?

ecatalano
  • 687
  • 1
  • 4
  • 17

2 Answers2

12

LinkedListNode is not a type, but LinkedListNode<T> is. Be sure to implement LinkedListNode::LinkedListNode() and other member functions in the header file, and #include this header file before the definition of LinkedList<T>.

template <class T>
class LinkedList
{
private:
    LinkedListNode<T> *head;
    LinkedListNode<T> *current;
}
Community
  • 1
  • 1
YSC
  • 38,212
  • 9
  • 96
  • 149
3

Basically, compiler is saying that you do not have the type LinkedListNode, and compiler is right - LinkedListNode is a template, not a type. To form a type, you need to instantiate the template with an argument. For example, LinkedListNode<int> is a type.

However, your compiler could provide a better diagnostic. For example, g++ would:

4 : error: missing template arguments before 'x'

SergeyA
  • 61,605
  • 5
  • 78
  • 137