c++函数模板的使用

来源:互联网 发布:彩字制作软件 编辑:程序博客网 时间:2024/06/06 03:25
#include <iostream>//函数模板的使用//#define max(a,b)((a) > (b)?(a):(b))宏定义using namespace std;template<class type>type max(type a,type b) //整形数和实型数进行比较{ return (a > b) ? a : b;}char *max(char * a, char *b) //字符串的模板{ if (strcmp(a, b))  return a; else  return b;}void main() { double a, b; cin >> a >> b; cout << max(a, b) << endl;}//Example 2template <class type,int len>//定义一个模板类型type Max(type array[len]) //定义函数模板{ type ret = array[0];//定义一个变量 for (int i = 1; i < len; i++) //遍历数组元素 {  ret = (ret > array[i]) ? ret : array[i];//比较数组元素的大小 } return ret;//返回最大值}void main() { int array[5] = {1,2,3,4,5};// 定义一个整型数组 int iret = Max<int, 5>(array);//调用函数模板Max double dset[3] = {10.5,11.2,9.8};//定义实数数组 double dret = Max<double, 3>(dset);//调用函数模板Max cout << dret << endl;}
原创粉丝点击