Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not a class, namespace, or enumeration after making a template class?

Tags:

c++

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?

like image 829
ecatalano Avatar asked Mar 08 '16 15:03

ecatalano


2 Answers

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;
}
like image 52
YSC Avatar answered Nov 15 '22 18:11

YSC


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'

like image 22
SergeyA Avatar answered Nov 15 '22 20:11

SergeyA