I come, I see, I conquer

                    —Gaius Julius Caesar

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
/**************************重载函数模板匹配约定***************************
 * 1. 寻找和使用最符合函数名和参数类型的函数,若找到则调用它
 * 2. 否则,寻找一个函数模板,将其实例化产生一个匹配的模板函数,若找到则调用它
 * 3. 否则,寻找可以通过类型转换进行参数匹配的重载函数,若找到则调用它
 * 4. 如果按以上步骤均未找到匹配函数,则调用错误
 * 5. 如果调用有多于一个的匹配选择,则调用匹配出现二义性
 ************************************************************************
*/

#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=10char 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.35.66.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

posted on 2008-01-26 20:42  jcsu  阅读(1188)  评论(0编辑  收藏  举报