例13-1求两个数最大值的函数模板#include<iostream>#include<string>using namespace std:template< class T>//模板声明,T为类型参数,或<typename T>Max(T a,T b) //<类型><函数名>(<参数表>)return a>b?a:b;
例13-1 求两个数最大值的函数模板 5 #include<iostream> #include<string> using namespace std; template < class T > //模板声明,T为类型参数,或<typename T> Max(T a, T b) //<类型><函数名>(<参数表>) { return a>b?a:b; }
/测试用主函数Typeint:5int mainOdouble:5.2TypeTypestring:xjtuint i1 = 3, i2 = 5:double d1 = 3.3, d2 = 5.2:string str1("xjtu"), str2("xian"):cout << "Type int: " << Max(il, i2) << endl:cout << "Type double: " << Max(dl, d2) << endl;cout <<"Type string: " <<Max(strl, str2)<< endl:return O;人D
6 //测试用主函数 int main() { int i1 = 3, i2 = 5; double d1 = 3.3, d2 = 5.2; string str1("xjtu"), str2("xian"); cout << "Type int: " << Max(i1, i2) << endl; cout << "Type double: " << Max(d1, d2) << endl; cout << "Type string: " << Max(str1, str2) << endl; return 0; }
3、使用函数模板的注意事项(1)在函数模板的参数表中,至少有一个参数的类型为模板的类型参数(2)函数的返回值的类型也可以是该类型参数。(3)模板中可以带有多个参数类型例如:template <class T1, class T2, class T3>void func1(T1 arg1 , T2 arg2, T3 arg3)..7
3、使用函数模板的注意事项 7 (1)在函数模板的参数表中,至少有一个参 数的类型为模板的类型参数。 (2)函数的返回值的类型也可以是该类型参 数。 (3)模板中可以带有多个参数类型。 例如: template <class T1, class T2, class T3> void func1(T1 arg1,T2 arg2, T3 arg3) { . }
(4)函数可以带有模板参数表中未给出的已存在的数据类型的参数例如 :template < class T >T func2(T argl , int arg2)Y人
8 (4)函数可以带有模板参数表中未给出的、 已存在的数据类型的参数。 例如: template < class T > T func2(T arg1,int arg2) { . }
例13-4:方幂为正整数的幂函数模板template < class T >T Power(T a, int m)Ty=a,while(--m>0)//m=m-1;m>0( y*=a;return y
例13-4:方幂为正整数的幂函数模板 9 template < class T > T Power(T a, int m) { T y = a; while(-m>0) //m=m-1;m>0 { y*=a; } return y; }