c++模板函数
Posted mch5201314
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++模板函数相关的知识,希望对你有一定的参考价值。
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++模板函数的主要内容,如果未能解决你的问题,请参考以下文章