C++函数模板入门实例

来源:互联网 发布:mac npm 全局安装路径 编辑:程序博客网 时间:2024/05/21 22:59

C++提供了函数模板的功能,通过函数模板,简化了函数重载,作为一项技术,下面给出一个入门实例,能很好的理解函数模板功能和作用。

 

 

 

  1. #include <iostream>
  2. using namespace std;
  3. template<typename Type> Type larger(Type x,Type y);
  4. void main()
  5. {
  6.     cout<<"larger of 1 and 2 = "<<larger(1,2)<<endl;
  7.     cout<<"line2:larger of A and B = "<<larger('A','B')<<endl;
  8.     cout<<"line3:larger of 5.5 and 3.3 = "<<larger(5.5,3.3)<<endl;
  9.     char str1[]="Hello";
  10.     char str2[]="Hella";
  11.     cout<<str1<<" and "<<str2<<"= "<<larger(str1,str2)<<endl;
  12. }
  13. template<typename Type> Type larger(Type x,Type y)
  14. {
  15.     if(x>=y)
  16.         return x;
  17.     else
  18.         return y;
  19. }

通过调用larger函数模板,可以实现多种数据类型的比较。