C++模板

���Ľ�������л�����Ķ�

函数模板

以前的重载,是函数名字相同,函数体不同,返回值类型不同,参数类型不同,参数个数不同,参数顺序不同。

函数模板是一个统一的函数,它可以适应一定范围内的不同类型的对象操作。函数模板将代表着不同类型的一组函数,他们都使用相同的代码。

定义

1
2
3
4
5
template <参数化类型名列表>
返回值类型 函数名(参数列表)
{
函数体
}

其中:template是定义模板的关键字, <参数化类型名列表>是模板参数列表,多个表项用逗号隔开。
格式如下:

1
2
3
4
class 标识符1class 标识符2
//这里的标识符1,标识符2是模板参数,class是修饰符,表示后面其后面的标识符是参数化的类型名,即模板参数。
//例如
template <class T1, class T2>

例子:

1
2
3
4
5
6
7
8
template <class T>
void swap(T &a,T &b)
{
T t;
t = a;
a = b;
b = t;
}

函数模板与模板函数

函数模板是模板函数的一个样板,它可以生成多个重载的模板函数,这些模板函数重用函数体代码。
模板函数是函数模板的一个实例。

函数模板的实验

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream.h>
template <class T>
T max(T a, Tb){
return a>b?a:b;
}
void main(){
int n1 = 8, n2 = 9;
double m1 = 3.14, m2 = 3.15;
char c1 = 'm', m2 = 'n';
cout<<"max(n1,n2)="<<max(n1,n2)<<endl;
cout<<"max(m1,m2)="<<max(m1,m2)<<endl;
cout<<"max(c1,c2)="<<max(c1,c2)<<endl;
}

执行结果为:

1
2
3
max(n1,n2)=9
max(m1,m2)=3.15
max(c1,c2)=n

说明:定义了一个函数模板,名字是max,有一个模板参数T。主函数中使用int,char,double代替了模板参数T。

冒泡排序(使用函数模板)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream.h>
#include <string.h>
template <class stype>
void bubble(stype * item,int count);

template <class stype>
void bubble(stype *item,int count)
{
register i,j;
stype t;
for(i=1;i<count;i++)
for(j=count-1;j>=i;j--){
if(item[j-1]>item[j]){
t = item[j-1];
item[j-1] = item[j];
item[j] = t;
}
}
}
0%