今天网上找到一个C++类模板的简洁明了的例子:
#include "iostream.h"
#include "stdlib.h"
//结构体
struct Student
{
int id;
int age;
};
//类模板
template <class T>
class Store
{
private:
T item;
int haveValue;
public:
Store(void);
T GetElem(void);
void PutElem(T x);
};
template <class T>
Store <T>::Store(void):haveValue(0)
{}
template <class T>
T Store <T>::GetElem(void)
{
//如果试图提取未初始化的程序,则终止程序
if(haveValue==0)
{
cout<<"No item present!"<<endl;
exit(1);
}
return item;
}
//存入数据函数的实现
template <class T>
void Store <T>::PutElem(T x)
{
haveValue++;
item = x;
}
void main(void)
{
Student g={1000,23};
//声明Student类型结构体变量的同时赋以初值
Store<int> S1,S2;
//声明两个Store类对象,其中数据成员item为int类型
Store<Student> S3;
//都必须明Store类对象S3,其中数据成员item为Student类型
Store<double> D;
S1.PutElem(3);
S2.PutElem(-7);
cout<<S1.GetElem()<<" "<<S2.GetElem()<<endl;
//输出对象S1和S2的数据成员
S3.PutElem(g);
cout<<"The Student id is "<<S3.GetElem().id<<endl;
//输出对象S3的数据成员
cout<<"Retrieving object D ";
cout<<D.GetElem()<<endl;
//由于D未初始化,在执行函数D.GetElement()过程中导致程序终止
}