泛型程序设计 generic programing
算法在实现十不指定具体要操作的数据类型的程序设计方法。
1.函数模板
template<class para1,class para2,...>
返回值类型 模板名(paras..){
函数体;
}
e.g.
template<class T>
void swap(T &a,T &b){
T temp = a;
a = b;
b = temp;
}
编译器由模板自动生成函数时。会用具体的类型名对模板中所有的类型参数进行替换。其他部分原封不动照抄。
此过程称为模板的实例化。得到模板函数!
新标准中的一个例子:
#include"iostream"
using namespace std;
/*
template<class T>
void print (const T array[],int size){
int i ;
for(i=0; i<size; i++){cout<<array[i];}
return;
}
*/
void swap(int &x,int &y){
int temp;
temp = x;
x = y;
y = temp;
}
void swap2(int x,int y){
int temp;
temp = x;
x = y;
y = temp;
}
template<class T>
T MaxElement(T a[],int size){
T max = a[0];
int i;
for(i=1; i<size; i++){
if(a[i]>max){
max = a[i];
}
}
return max;
}
class CFraction
{
public:
int num1,num2;
CFraction(int n1,int n2):num1(n1),num2(n2){};
bool operator > (const CFraction &f)const{
if(num1*f.num2>0)
return num1*f.num2>f.num1*num2;
else
return num1*f.num2<f.num1*num2;
}
bool operator == (const CFraction &f) const{
return num1*f.num2 == num2*f.num1;
}
friend ostream &operator <<(ostream &o,const CFraction &f);
};
ostream &operator <<(ostream &o,const CFraction &f){
o << f.num1 << "/" << f.num2;
return o;
}
int main(){
int a[5]={1,2,3,4,5};
CFraction f[4] = {CFraction(1,2),CFraction(1,4),CFraction(-5,7),CFraction(2,3)};
cout<<MaxElement(a,5)<<endl;
cout<<MaxElement(f,4)<<endl;
return 0;
}
从上个例子可以看出,类型参数不但可以用来定义参数类型,还能用于定义局部变量和函数模板的返回值类型。
2.类模板
跟函数模板类似,当用到比较类似的类的时候可以使用
Template <para1>
class name1{
...members...
};
同样举个例子说明:
template<class T1,class T2>
class pair{
T1 key;
T2 value;
pair(T1 k,T2 v):key(k),value(v){};
};
int main(){
pair<string ,int>student ("Tom",19);
return 0;
}
同样有类模板的实例化,模板类的概念。
好吧 今天就到这里。明天继续!