C++提供了函数模板的功能,通过函数模板,简化了函数重载,作为一项技术,下面给出一个入门实例,能很好的理解函数模板功能和作用。
- #include <iostream>
- using namespace std;
- template<typename Type> Type larger(Type x,Type y);
- void main()
- {
- cout<<"larger of 1 and 2 = "<<larger(1,2)<<endl;
- cout<<"line2:larger of A and B = "<<larger('A','B')<<endl;
- cout<<"line3:larger of 5.5 and 3.3 = "<<larger(5.5,3.3)<<endl;
- char str1[]="Hello";
- char str2[]="Hella";
- cout<<str1<<" and "<<str2<<"= "<<larger(str1,str2)<<endl;
- }
- template<typename Type> Type larger(Type x,Type y)
- {
- if(x>=y)
- return x;
- else
- return y;
- }
通过调用larger函数模板,可以实现多种数据类型的比较。