编写函数模板的一般方法:
(1)定义一个普通的函数,数据类型采用具体的普通的数据类型。
(2)将数据类型参数化。
(3)在函数头前用关键字template引出对类型参数名的声明。
- <span style="font-size:18px;">#include<iostream>
- using namespace std;
- template <class T>
- T min(T x, T y)
- {
- if(x < y)
- return x;
- else
- return y;
- }
- int main()
- {
- int n1=2, n2=10;
- double d1=1.5, d2=5.6;
- cout<<"较小的整数:"<<min(n1,n2)<<endl;
- cout<<"较小的实数:"<<min(d1,d2)<<endl;
- return 0;
- }</span>
- #include<iostream>
- using namespace std;
- class MyClass
- {
- int x, y;
- public:
- MyClass(int x1, int y1){
- x = x1;
- y = y1;
- }
- int getx(){return x;}
- int gety(){return y;}
- int operator<(MyClass &c){//重载运算符"<"
- if(x<c.x && y<c.y)
- return 1;
- else
- return 0;
- }
- };
- template <class T> //函数模板声明
- T &min(T &o1, T &o2)
- {
- if(o1 < o2)
- return o1;
- else
- return o2;
- }
- int main()
- {
- MyClass s1(5,1);
- MyClass s2(6,18);
- MyClass s3(min(s1, s2)); //利用重载<运算符比较两个MyClass对象
- cout<<"较小的坐标:("<<s3.getx()<<","<<s3.gety()<<")"<<endl;
- double d1=3.25;
- double d2=2.54;
- cout<<"较小的数:"<<min(d1,d2)<<endl;//利用标准<运算符比较两个实数
- return 0;
- }