函数模板与同名的非模板函数重载方法所遵守的规定

寻找一个参数完全匹配的函数,如果找到了就调用它;

  1. 如果失败,寻找一具函数模板,使其它实例化,产生一个匹配的模板函数,如果找到了,就调用它;
  2. 如果失败,再试低一级的对函数重载的方法,例如通过类型转换可产生的参数匹配等,如果找到了匹配的函数,就调用它;
  3. 如果失败,则证明这是一个错误的调用。

下面是一个例子:

#include <iostream.h>
template <class T>
T max(T x, T y)
{
    cout<< "this is template function! max is:";
    return (x>y)? x : y;
}

int max(int x, int y)
{
    count<< "this is overload function with int, int! max is: ";
    return (x>y)? x : y;
}

char max(int x, char y)
{
    count<< "this is the overload function with int, char! max is: ";
    return (x>y)? x : y;
}

main()
{
    int i=10;
    char c = 'a';
    float f = 43.74;
    count<<max(i, i)<<endl;
    count<<max(c, c)<<endl;
    count<<max(i, c)<<endl;
    count<<max(c, i)<<endl;
    count<<max(f, f)<<endl;
    count<<max(f, i)<<endl;
    return 0;
}

结果为:

this is the overload function with int, int! max is: 10
this is a template function! max is: a
this is the overload function with int, char! max is: a
this is the overload function with int, int! max is: 97
this is a template function! max is 43.740001
this is the overload function with int, int! max is: 43

请注意在上面的函数中,转化数据类型时先转换第一个参数