模板——函数模板

//《C++编程——数据结构与程序设计方法》例15.8

//利用函数重载技术,求两个整数、字符、浮点数或字符串中的较大值,需要编写4个函数larger。
//而C++通过提供函数模板,简化了重载函数据的过程。

#include <iostream>
using namespace std;

template<class Type>//Type,模板的形参,用于确定函数的形参,返回值类型,还用于在函数中声明变量。
Type larger(Type x,Type y);

int main()
{
 cout<<"Line 1: Larger of 5 and 6 ="<<larger(5,6)<<endl;
 //由于5和6是int类型,编译器会自动用int取代Type,产生相应代码,以下同理。
 cout<<"Line 2: Larger of A and B ="<<larger('A','B')<<endl;
 cout<<"Line 3: Larger of 5.6 and 3.2 ="<<larger(5.6,3.2)<<endl;

 char str1[]="Hello";
 char str2[]="Happy";

 cout<<"Line 6: Larger of "<<str1<<" and "<<str2<<" = "<<larger(str1,str2)<<endl;

 return 0;
}

template<class Type>
Type larger(Type x,Type y)
{
 if(x>=y)
  return x;
 else
  return y;
}

原文地址:https://www.cnblogs.com/WestGarden/p/3138421.html