Help with my template stack

Started by
3 comments, last by Monkan 13 years, 6 months ago
Hi, my first post so i hope it all comes out ok.
Im making a templated stack but Im getting some grief and not too sure what Ive done wrong. Its saying Ive got an unresolved external when trying to make a new stack. Any help would be much appreciated.

Stack.h
#pragma oncetemplate <class Type>class Stack{private:			typedef struct node	{ 			Type item;		node *next;	} snode;	snode *top, *z;   public:	Stack();	~Stack(){};	Type Pop(void);	void Push(Type argItem);	bool IsEmpty(void);	     };


Stack.cpp
#include <iostream>using namespace std;#include "Stack.h"template <class Type>Stack<Type>::Stack(){	z = new snode;	z->next  = z;		top = new snode;		top->next = z;	}template <class Type>void Stack<Type>::Push(Type argItem){	snode *temp;	temp = top;	top = new snode;	top->next = temp;	top->item = argItem;}template <class Type>bool Stack<Type>::IsEmpty(void){     if( top->next == z)	    return true;	 else		 return false;	 }template <class Type>Type Stack<Type>::Pop(void){		Type returnItem;	if (isEmpty())	{		cout<<"\n   empty   ";		return null;	}        returnItem = top->item;	snode *temp;	temp = top;	top = top->next;		delete temp;		return returnItem;};


"To know the road ahead, ask those coming back."

Advertisement
In short, the compilation unit must know the definitions of the template functions/classes it tries to instantiate.

See sections 35.12 and 35.13 of the almighty C++ FAQ for more details.
In easy terms never define a template implementation in a CPP file this doesn't work as the compiler can't find the code it needs to generate for the type with which you are initialising the stack template.

If you want to split it off from the header use a .hpp or .inl or whatever extension you want and after your class declaration in the header use #include "whateveryounamedyourfile.extension" .

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

Quote:Original post by NightCreature83
In easy terms never define a template implementation in a CPP file this doesn't work as the compiler can't find the code


With the one exception of explicit instantiation, but it's irrelevant in almost all cases.
That's done it,

Thanks for the help.

"To know the road ahead, ask those coming back."

This topic is closed to new replies.

Advertisement