template <typename T>

inline T const& max(T const& r,T const& l)

{

std::cout<<"same T template"<<std::endl;

return r < l ? l : r;

}

对于以上的模板定义,对于调用max(42.0,43)产生错误,对于这种错误有三种方式:

1、对实参进行强制类型转换,使它们可以互相匹配,如下:

max(static_cast<double>(4),4.2)

2、显式指定(或者限定)T的类型,如下:

max<double>(4,4.2)

3、指定两个参数可以具有不同的类型


 

*********************************************************


 

函数模板无法指定默认的模板实参,如下的函数定义将会产生一个编译错误,

template <typename T1,typename T2 = int>

inline T1 const& max(T1 const& r,T2 const& l)

{

std::cout<<"different T template"<<std::endl;

return r < l ? l : r;

}

gcc下编译产生如下错误:

error: default template arguments may not be used in function templates


 

*********************************************************


 

当模板函数声明定义顺序如下(下称顺序1),当调用三个int型变量的max函数时,会调用重载的int版本。

template <typename T>

inline T const& max(T const& r,T const& l)

{

std::cout<<"same T template"<<std::endl;

return r < l ? l : r;

}


 

inline int const& max(int const& r,int const& l)

{

std::cout<<"same int template"<<std::endl;

return r < l ? l:r;

}


 

template <typename T>

inline T const& max(T const& a,T const& b,T const& c)

{

return max(max(a,b),c);

}


 

当模板函数声明定义顺序如下(下称顺序2),当调用三个int型变量的max函数时,会调用函数的模板版本

template <typename T>

inline T const& max(T const& r,T const& l)

{

std::cout<<"same T template"<<std::endl;

return r < l ? l : r;

}


 

template <typename T>

inline T const& max(T const& a,T const& b,T const& c)

{

return max(max(a,b),c);

}


 

inline int const& max(int const& r,int const& l)

{

std::cout<<"same int template"<<std::endl;

return r < l ? l:r;

}


 

当模板函数声明定义顺序为顺序1时,但将int函数声明放置在调用之前,当调用三个int型变量的max函数时,会调用函数的int重载版本

int const& max(int const& r,int const& l);

template <typename T>

inline T const& max(T const& r,T const& l)

{

std::cout<<"same T template"<<std::endl;

return r < l ? l : r;

}


 

template <typename T>

inline T const& max(T const& a,T const& b,T const& c)

{

return max(max(a,b),c);

}


 

inline int const& max(int const& r,int const& l)

{

std::cout<<"same int template"<<std::endl;

return r < l ? l:r;

}

由上所述,函数的所有重载版本的声明都应该位于该函数被调用的位置之前。