A template is a way to reuse code without having to worry about the types you use......so if you construct a neat container for ints and you want to reuse it for chars, then you dont have to rewrite the container.......for this to be effective though, the purpose of the template you create must not be effected by the types you wish to use...therefore they are great for containers (lists,stacks,queues..etc)
Here's a slightly brief version of a stack that I can use with both ints and chars without having to change any of the template's code
Code:
#include <iostream>
using std::cout;
using std::endl;
template<class T>
class MyStack{
struct Node{
T Data;
Node* Next;
Node(const T& newData,Node* newNext)
:Data(newData),Next(newNext){};
};
Node* Top;
public:
void Push(const T& newData){Top = new Node(newData,Top);}
T Pop(){
Node *n = Top;
Top = Top->Next;
T RetData = n->Data;
delete n;
return RetData;
}
MyStack():Top(0){}
~MyStack(){
while(Top){
Node *n = Top;
Top = Top->Next;
delete n;
}
}
};
int main(){
MyStack<int> *m = new MyStack<int>;
cout << "Now for some numbers" << endl;
m->Push(10);
m->Push(15);
cout << m->Pop() << endl;
cout << m->Pop() << endl;
delete m;
MyStack<char> *n = new MyStack<char>;
cout << "Now for some chars" << endl;
n->Push('y');
n->Push('d');
n->Push('r');
n->Push('o');
n->Push('f');
cout << n->Pop();
cout << n->Pop();
cout << n->Pop();
cout << n->Pop();
cout << n->Pop();
cout << endl;
delete n;
return 0;
}