c++:类模板

#include<iostream>
#include<cstdlib>
using namespace std;
struct Student{
	int id;
	float gpa;
};
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()
{
	Student g = { 1000, 23.0};
	Store<int>S1, S2;
	Store<Student>S3;
	Store<double>D;
	S1.putElem(3);
	S2.putElem(-7);
	cout << S1.getElem() << "," << S2.getElem() << endl;
	S3.putElem(g);
	cout << "the student id is:" << S3.getElem().id << endl;
	cout << "object D:";
	cout << D.getElem() << endl;
}

原文地址:https://www.cnblogs.com/javafly/p/6037241.html