基本用法:
模板定义:
template <class type>
type Sum(type xvar, type yvar){
return xvar+yvar;
}
模板定义二:
template <class type,int len>
type GetMax(type array[len]){
type ret=array[0];
for(int i=1;i<len;i++){
ret = (ret>array[i])?ret:array[i];
}
return ret;
}
使用方法:
int _tmain(int argc, _TCHAR* argv[])
{
int iRet=Sum<int>(10,20);
printf("%d\n",iRet);
int array[5] = {1,2,3,4,5};
int iret = GetMax<int,5>(array);
printf("%d\n",iret);
double dset[3] = {10.5,11.2,9.8};
double dret = GetMax<double,3>(dset);
printf("%f\n",dret);
return 0;
}
下面是完整的代码:
template <class type>
type Sum(type xvar, type yvar){
return xvar+yvar;
}
template <class type,int len>
type GetMax(type array[len]){
type ret=array[0];
for(int i=1;i<len;i++){
ret = (ret>array[i])?ret:array[i];
}
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
int iRet=Sum<int>(10,20);
printf("%d\n",iRet);
int array[5] = {1,2,3,4,5};
int iret = GetMax<int,5>(array);
printf("%d\n",iret);
double dset[3] = {10.5,11.2,9.8};
double dret = GetMax<double,3>(dset);
printf("%f\n",dret);
return 0;
}
模板重载:
template <class type>
type Sum(type xvar, type yvar){
return xvar+yvar;
}
template <class type>
type Sum(type array[],int len){
type ret=0;
for(int i=0;i<len;i++){
ret += array[i];
}
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
int iret=Sum(10,20);
printf("整数之和:%d\n",iret);
int array[5] = {1,2,3,4,5};
int ret=Sum(array,5);
printf("数组元素之和:%d\n",ret);
return 0;
}