compiling template example

M

mfabricius

Hi,

I am sure it's silly.

I get the error:
/tmp/ccyVx871.o: In function `main':
UseStack.cpp:(.text+0x8b): undefined reference to `Stack<int>::Stack()'
UseStack.cpp:(.text+0x9e): undefined reference to
`Stack<int>::push(int)'
UseStack.cpp:(.text+0xa9): undefined reference to `Stack<int>::pop()'
UseStack.cpp:(.text+0xea): undefined reference to
`Stack<int>::~Stack()'
UseStack.cpp:(.text+0x105): undefined reference to
`Stack<int>::~Stack()'
collect2: ld returned 1 exit status

when I try to compile following code. If I put main() into Stack.cpp it
works. What am I missing?
(I use g++ 4.1.2)

Thanks!

Max

Stack.h:
-----------------------------
#ifndef _Stack_h
#define _Stack_h
template <class T>
class Stack {
protected:
struct elem{
T value;
elem* next;
};

elem* current;
int count;

public:
void push(T);
T pop();
Stack() ;
~Stack();

};

Stack.cpp:
-----------------------------
#include "Stack.h"

#include<iostream>

using namespace std;

template <class T>
void Stack<T>::push(T value)
{
elem* e = new elem;
e->value = value;
e->next = Stack::current;
Stack::current = e;
Stack::count++;
}

template <class T>
T Stack<T>::pop()
{
if (Stack::count == 0 ){
cerr << "Error: Stack empty!\n",
exit(-1);
}else{
elem* e = Stack::current;
Stack::current = e->next;
Stack::count--;
T v = e->value;
delete e;
return v;
}

}


template <class T>
Stack<T>::Stack(){
current = 0;
count = 0;
}

template <class T>
Stack<T>::~Stack(){
while(count > 0)
Stack::pop();

}

UseStack.cpp:
-----------------------------
#include "Stack.h"
#include <iostream>
#include <vector>
#include "Stack.h"


using namespace std;
int main(){
Stack<int> a;
a.push(5);
std::cout << "Value : " << a.pop() << "\n";
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top