码迷,mamicode.com
首页 > 编程语言 > 详细

c++模板函数

时间:2019-09-12 13:11:05      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:std   模板   class   参数不匹配   color   ble   --   bit   main   

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 template <class T>
 4 T Min(T a,T b)
 5 {
 6     return (a < b)?a:b;
 7 }
 8 
 9 int main()
10 {
11     double a = 2,b = 3.4;
12     float c = 2.3,d = 3.2;
13    // 模板参数不匹配解决方案
14    //1.调用时进行类型强制转换
15     cout << "2,3.2 min is " << Min(double(2),3.2) << endl;
16     cout << "a,c min is " << Min(a,double(c)) << endl;
17     cout << "a,3 min is " << Min(int(a),3) << endl;
18     //2.显示指定函数模板实例化的类型参数
19     cout << "-------------------->" << endl;
20     cout << "2,3.2 min is " << Min<double>(2,3.2) << endl;
21     cout << "a,c min is " << Min<double>(a,c) << endl;
22     cout << "a,3 min is " << Min<int>(a,3) << endl;
23     //3.指定多个模板参数,下一份程序写
24 
25     return 0;
26 }

第三种解决方案:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 template <class T1,class T2>
 4 T1 Min(T1 a,T2 b)
 5 {
 6     return (a < b) ? a:b;
 7 }
 8 
 9 int main()
10 {
11     double a = 2,b = 3.4;
12     float c = 2.3,d = 3.2;
13     cout << "-------------------->" << endl;
14     cout << "2,3.2 min is " << Min(2,3.2) << endl;
15     cout << "a,c min is " << Min(a,c) << endl;
16     cout << "a,3 min is " << Min(a,3) << endl;
17     return 0;
18 }

 

c++模板函数

标签:std   模板   class   参数不匹配   color   ble   --   bit   main   

原文地址:https://www.cnblogs.com/mch5201314/p/11511164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!