**************************重载函数模板匹配约定***************************
同名的函数模板、模板显式特化函数和普通函数的优先选择顺序,总结出以下4点:
1.如果参数类型以及返回类型完全匹配,则选择普通函数或者模板显式特化函数作为调用的函数实例。
2.否则,如果模板函数能够推导出一个参数类型以及返回类型完全匹配的函数实例,则选择函数模板。
3.否则,如果调用函数的实参以及返回类型能够进行隐式转换成与普通函数或者模板显式特化函数的类型匹配,则选择普通函数或者模板显式特化函数。
4.如果以上三条都不能匹配,则函数匹配失败,发生编译错误。
*************************************************************************/
#include <iostream>
using namespace std;
template <class T>
const T & Max(const T &x, const T &y) //函数模板
{
cout<<"A template function! Max is: ";
return (x>y) ? x : y;
}
template <class T>
const T & Max(const T &a, const T &b, const T &c) //重载函数模板
{
T s; s=Max(a,b); return Max(s,c);
}
const int & Max(const int &x, const int &y) //用普通函数重载函数模板
{
cout<<"An overload function with int, int! Max is: ";
return (x>y) ? x : y;
}
const char Max(const int &x, char const &y) //用普通函数重载函数模板
{
cout<<"An overload function with int, char! Max is: ";
return (x>y) ? x : y;
}
void main()
{
int i=10; char c='a'; double f=98.74;
cout<<Max(i, i)<<endl;
cout<<Max(c, c)<<endl;
cout<<"Max(3.3, 5.6, 6.6) is "<<Max(3.3, 5.6, 6.6)<<endl;
cout<<Max(i, c)<<endl;
cout<<Max(c, i)<<endl;
cout<<Max(f, f)<<endl;
cout<<Max(f, i)<<endl;
cout<<Max(i, f)<<endl;
}
输出结果:
An overload function with int, int! Max is: 10
A template function! Max is: a
A template function! Max is: A template function! Max is: Max(3.3, 5.6, 6.6) is 6.6
An overload function with int, char! Max is: a
An overload function with int, char! Max is: a
A template function! Max is: 98.74
An overload function with int, char! Max is: b
An overload function with int, char! Max is: b