函数模板中使用多种类型
#include<iostream>
using namespace std;template <class T1,class T2>
void Swap( T1&a,T2&b)
{
T1 t;
t=a;
a=T1(b);
b=T2(t);
}
void main()
{
int x=5;
char y='c';
cout<<x<<","<<y<<endl;
Swap(x,y);
cout<<char(x)<<","<<int(y)<<endl;
system("pause");
}
函数模板 实例
#include<iostream>
using namespace std;
template <class T>
T max(T x,T y);
void main()
{
float a=5.2,b=8.5;
char c='d',d='D';
cout<<Max(a,b)<<endl;
cout<<Max(c,d)<<endl;
system("pause");
}
template<class T>
T Max( T x,T y)
{
if (x>=y) return x;
return y;
}
函数模板重载
#include<iostream>
using namespace std;
float sum(float One,float Two)
{
return One+Two;
}
template <class T>
T sum( T One, T two, T three)
{
return One+two+three;
}
void main()
{
int a=1,b=2,c=3;
cout<<sum(a,b)<<endl;
cout<<sum(a,b,c)<<endl;
system("pause");
}