函数模板(Function Template)
所谓函数模板,实际上就是建立一个通用函数
1、函数定义时不指定具体的数据类型(使用虚拟类型代替)
2、函数被调用时编译器根据实参反推数据类型-类型的参数化
//模板头与函数声明/定义永远是不可分割的整体!
template<typename 类型参数1,typename 类型参数2,...>//typename老版C++用class
返回值类型 函数名(形参列表){
//函数体中可以使用类型参数
}
补:
template<typename T>
template<class T> //早期写法
例:定义排序函数
#include<iostream>
using namespace std;
template<typename T> void Sort(T tArray[],int len);
int main()
{
int a[]={10 ,55,11,59,15};
Sort(a,5);
for(int i=0;i<5;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
template<typename T> void Sort(T tArray[],int len)
{
for(int i=0;i<len-1;i++)
{
for(int j=0;j<len-i-1;j++)
{
if(tArray[j]>tArray[j+1])
{
T temp=tArray[j];
tArray[j]=tArray[j+1];
tArray[j+1]=temp;
}
}
}
}
(注:函数模板不代替重载)