Reputation: 73
I am learning C++ templates for the first time, and have copied this code from "Data Structures and Algorithms in C++ by Michael Goodrich."
I get the error "Line 13: SLinkedList is not a template." I am at a complete loss as to why it is not since I have used "template " everywhere.
// ------------------ DEFINITION FOR NODE ------------------------
template <typename E>
class SNode{
private:
E elem;
SNode<E>* next;
friend class SLinkedList<E>;
public:
SNode(E element = NULL);
const E getElem() const;
void setElem(E element);
};
template <typename E>
SNode<E>::SNode(E element){ elem = element;}
template <typename E>
const E SNode<E>::getElem() const
{return elem;}
template <typename E>
void SNode<E>::setElem(E element)
{elem = element;}
// -------------------- DEFINITION FOR SINGLY-LINKED LIST --------------
template <typename E>
class SLinkedList
{
private:
SNode<E>* head;
public:
SLinkedList();
~SLinkedList();
bool isempty() const;
const E& infront() const;
void addfront(const E& e);
void removefront();
};
template <typename E>
SLinkedList<E>::SLinkedList()
:head(NULL) {}
template <typename E>
SLinkedList<E>::~SLinkedList()
{while(!isempty()) removefront();}
template <typename E>
bool SLinkedList<E>::isempty() const
{return (head == NULL);}
template <typename E>
const E& SLinkedList<E>::infront() const {return head->elem;}
template <typename E>
void SLinkedList<E>::addfront(const E& element) {
SNode<E>* v = new SNode<E>;
v->elem = element;
v->next = head;
head = v;
}
template <typename E>
void SLinkedList<E>::removefront() {
SNode<E>* old = head;
head = old->next;
delete old;
}
int main()
{
std::cout<<"Checking SLinkedList ..."<<std::endl<<std::endl;
SLinkedList<int> intList;
intList.addfront(13);
std::cout<<intList.head->next->getElem();
return 0;
}
Upvotes: 1
Views: 188
Reputation: 57545
friend class SLinkedList<E>;
This can be anything. The compiler doesn't know what it is. But if you tell him before declaring SNode
that it will be defined later...:
template <typename E>
class SLinkedList;
... it might work ;)
Upvotes: 2
Reputation: 9380
You are using SLinkedList<E>
even before declaring it. Before using it in you class `SNode', please declare it which is known as forward declaration.
Upvotes: 2