函数模板简介
模板是C++的高级特性,分为函数模板和类模板,使用模板能够快速建立具有类型安全的类库合集和函数合集。
这里我们主要介绍函数模板
函数模板不是一个实在的函数,编译器不能为其生成可执行代码。定义函数模板最后只是一个对函数功能框架的描述,当它具体执行时,将根据传递的实际参数决定功能。
函数模板的定义
1 2 3 4
| template <参数类型及参数> 返回类型 函数名 (形式参数) { }
|
也可以声明函数模板分成template部分和函数部分:
1 2 3 4 5
| template <参数类型> 返回类型 函数名 (形式参数) { }
|
template为关键字,表示定义一个模板。
<>表示模板参数,模板参数有两种,是模板类型参数、模板非类型参数。模板类型参数使用关键字class或typedef开始,后面跟一个合法类型名。模板非类型参数与普通参数定义相同,通常是一个常数。可以不使用模板非类型参数。
下面以求和函数为例解释函数模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include<iostream> using namespace std;
template <class type> type sum(type x,type y) { return x+y; } int main() { int a=3; int b=5; int s=sum<int>(a,b); cout<<s<<endl; double c=1.23; double d=2.45; double m=sum<double>(c,d); cout<<m; return 0; }
|
对如上代码进行解释:
首先是声明一个模板template<calss type>
,然后是定义函数模板的具体实现方法
1 2 3 4 5
| type sum(type x,type y) { return x+y; }
|
相比之下,模板函数在声明类型的情况下可以实现各种运算,而自定义函数只能实现单纯的int运算。
所以,定义函数模板的有点就是适应各种类型对象的计算和输出。
最后就是函数模板的调用
1 2
| int s=sum<int>(a,b); double m=sum<double>(c,d);
|
这里的int和double就是使用模板的方式,即模板类型。若除去<>,就变成了
1 2
| int s=sum(a,b); double m=sum(c,d);
|
这个跟自定义函数的使用方法相同。
函数模板入门应用
使用数组作为模板参数,分别输出int数组和double数组的最大值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include<iostream> using namespace std; template <class type,int len> type max(type a[]) { type m=a[0]; for(int i=0;i<len;i++) { if(a[i]>m) { m=a[i]; } } return m; } int main() { int x[]={1,2,3,4,5}; double y[]={1.2,2.5,1.6,5.6,7.8,4.6}; cout<<"The max int is:"<<max<int,sizeof(x)/sizeof(x[0])>(x)<<endl; cout<<"The max double is:"<<max<double,sizeof(y)/sizeof(y[0])>(y); return 0; }
|