Sign in to follow this  
Monkan

Help with my template stack

Recommended Posts

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 once

template <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;
};




Share this post


Link to post
Share on other sites
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" .

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this