一、函数模板
#include<iostream>
using namespace std;
template<class T1,class T2>
T1 add(T1 x,T2 y)
{
cout<<"("<<sizeof(T1)<<","<<sizeof(T2)<<")\t";
return x+y;
}
int main()
{
cout<<add(9,8)<<endl;
cout<<add(9.0,8.0)<<endl;
cout<<add(9,8.0)<<endl;
cout<<add(9.0,8)<<endl;
cout<<add('A','A'-'0')<<endl;
cout<<add(short(8),9)<<endl;
return 0;
}
二、类模板
#include<iostream>
#include<cstdio>
using namespace std;
template<class TNO,class TScore,int num>
class Student
{
private:
TNO StuID[num];
TScore score[num];
public:
void Put();
void Sort();
};
template<class TNO,class TScore,int num>
void Student<TNO,TScore,num>::Put()
{
for(int i=0;i<num;i++)
{
cin>>StuID[i];
cin>>score[i];
}
}
template<class TNO,class TScore,int num>
void Student<TNO,TScore,num>::Sort()
{
for(int i=0;i<num;i++)
{
for(int j=i+1;j<num;j++)
{
if(score[i]<score[j])
{
TScore st;
TNO nt;
st=score[i],nt=StuID[i];
score[i]=score[j],StuID[i]=StuID[j];
score[j]=st,StuID[j]=nt;
}
}
}
for(int i=0;i<num;i++)
{
cout<<StuID[i]<<" "<<score[i]<<endl;
}
}
int main()
{
Student<string,float,4>class1;
class1.Put();
class1.Sort();
}