函数模板(function template)是一个独立于类型的函数,可作为一种模式,产生函数的特定类型版本。
int abs( int x ){
return x<0?-x:x;
}
double abs( double x ){
return x<0?-x:x;
}
使用函数模板可以设计通用型的函数,这些函数与类型无关并且只在需要时自动实例化,从而形成“批量型”的编程方式。
函数模板定义的语法形式为:
template<模板形参表>返回类型 函数名(形参列表)
{
函数体
}
template<typename T>
T abs(T x){
return x<0?-x:x;
}
int main(){
int n=-5;
double d=-5.5;
cout<<abs(n)<<‘,’<<abs(d)<<endl;
return 0;
}
► 模板形参表(template parameter list)是用一对尖括号括< >括起来的一个或多个模板形参的列表,不允许为空,形参之间以逗号分隔,其形式有两种。
► ①第一种形式
typename 类型参数名1,typename 类型参数名2,…
► ②第二种形式
class 类型参数名1, class 类型参数名2,…
函数模板举例
include <iostream>
using namespace std;
template <class T> T add(T a,T b){
return a+b;
}
int main(){
cout<<"int_add="<<add(10,20)<<endl; //生成整型版本的add函数
cout<<"double_add="<<add(10.2,20.5)<<endl;//生成实型版本的add函数
cout<<"char_add="<<add('A','\2')<<endl;//生成字符型版本的add函数
cout<<"int_add="<<add(100,200)<<endl;
return 0;
}