1.函数模板之间的重载;
#include
using namespace std;
template
T const &max(T const &a,T const &b)
{
return a>b?a:b;
}
template
T const &max(T const &a,T const &b,T const &c)
{
T tmp =a>b?a:b;
return tmp>c?tmp:c;
}
void main()
{
cout<<"max(2,5)"<<max(2,5)<<endl;;
cout<<"max(1,7,6)"<<max(1,7,6)<<endl;
cout<<"max(12,7,4)"<<max(12,7,4)<<endl;
cout<<"max(12.6,12.65)"<<max(12.6,12.65)<<endl;
cout<<"max(12.60,12.66)"<<max(12.60,12.66)<<endl;
}
2.显示特化的重载;
#include
#include
using namespace std;
typedef const char*pCchar;
template
T max (T a,T b)
{
return (a>b?a:b);
}
template<>
pCchar max(pCchar a,pCchar b)
{
return (strcmp(a,b)>0?a:b);
}
void main()
{
cout<<"max(7,8)="<<max(7,8)<<endl;
pCchar str1="Hello";
pCchar str2="Hawkol";
cout<<"max(str1,str2)="<<max(str1,str2)<<endl;
cout<<"max('a','A')="<<max('a','A')<<endl;
}
3.普通函数之间的重载。
#include
using namespace std;
template
T max(T const &a,T const &b)
{
cout<<"in max template"<<endl;
return a>b?a:b;
}
int max(int const& a,int const &b)
{
cout<<"in max specific"<<endl;
return a>b?a:b;
}
void main()
{
cout<<"max(10,9)="<<max(10,9)<<endl;
cout<<"max('A','B')="<<max('A','B')<<endl;
cout<<"max(9.0.9.1)="<<max(9.0,9.1)<<endl;
}