原创地址:http://www.cnblogs.com/gw811/archive/2012/10/25/2738929.html
TemplateDemo.h
#include <iostream>
using namespace std;
#ifndef TEMPLATE_DEMO_HXX
#define TEMPLATE_DEMO_HXX
template<class T,int MAXSIZE> class Stack{
private:
T elems[MAXSIZE];
int numElems;
public:
Stack();
void push(T const&);
void pop();
T top() const;
bool empty() const{
return numElems == 0;
}
bool full() const{
return numElems == MAXSIZE;
}
};
template<class T,int MAXSIZE>
Stack<T,MAXSIZE>::Stack():numElems(0){}
template<class T,int MAXSIZE>
void Stack<T,MAXSIZE>::push(T const& elem){
if(numElems == MAXSIZE){
cout << "stack is pull" << endl;
}
elems[numElems++] = elem;
}
template<class T,int MAXSIZE>
void Stack<T,MAXSIZE>::pop(){
if(numElems <= 0){
cout << "stack is empty" << endl;
}
--numElems;
}
template<class T,int MAXSIZE>
T Stack<T,MAXSIZE>::top() const{
if(numElems <= 0){
cout << "stack is empty" << endl;
}
return elems[numElems-1];
}
#endif // TEMPLATH_DEMO_HXX
TemplateDemo.cpp
#include <iostream>
#include<string>
#include<cstdlib>
#include "TemplateDemo.h"
using namespace std;
int main(){
Stack<int,20> S20;
Stack<int,40> S40;
Stack<string,40> Str40;
S20.push(7);
cout << S20.top() << endl;
Str40.push("Hello");
cout << Str40.top() << endl;
}