Problem with class and template

i am trying to write a Stack class with template. but i've got 8 errors like this

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall stack<int>::stack<int>(int)" (??0?$stack@H@@QAE@H@Z) referenced in function _main

with every function mentioned.
But when i tried not to use template, rewrote this code with int, it worked properly.

here is my code
stack.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ifndef STACK_H
#define STACK_H

template <class T>
class stack{
	T *S;
	int maxSize, Top;//Top- index of the last elem
public:
	stack(int n=100);
	~stack();
	void push(T&);
	void pop();
	T& top();
	bool empty();
	bool full();
	int size();
	int maxsize();
	void clear();
};
	
#endif 


functions.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<iostream>
#include "stack.h"
#include<cassert>
using namespace std;

template <class T>
stack <T>::stack(int n){
	assert(n>0);
	S=new T[n]; assert(S);
	maxSize=n;
	Top=-1;
}

template <class T>
stack <T>::~stack(){
	delete[] S;
}

template <class T>
void stack <T> ::push(T& elem){
	assert(!full());
	S[++Top]=elem;
}

template <class T>
void stack <T>::pop(){
	assert(!empty());
	Top--;
}

template <class T>
T& stack <T>::top(){
	assert(!empty());
	return S[Top];
}

template <class T>
bool stack <T> ::empty(){
	return Top==-1;
}

template <class T>
bool stack <T>::full(){
	return Top==maxSize-1;
}

template <class T>
int stack <T>::maxsize(){
	return maxSize;
}

template <class T>
int stack <T>::size(){
	return Top+1;
}

template <class T>
void stack <T> ::clear(){
	assert(!empty());
	Top=-1;
}


main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include "stack.h"
using namespace std;

int main(){
	stack <int> St(15);
	int x;
	for(int i=0;i<=10;i++){
		cin>>x; St.push(x);
	}
	cout<<St.size()<<endl<<St.maxsize()<<endl;
	while(!St.empty()){
		cout<<St.top()<<endl;
		St.pop();
	}
	return 0;
}
When instantiating a templated object, the entire definition of the template class has to be known at compile time. This means that you have to include the entire definition of the template and its methods in the header file, rather than putting the method definitions in a separate .cpp file.

(There are other ways of dealing with this, but putting everything in the header is the standard way, for various reasons).
Topic archived. No new replies allowed.