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?
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;
}
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With