1.直接从例子来了解函数模板的概念:
template <class T>
inline
const T& min(const T& a,const T& b)
{
return b<a ? b : a;
}
运行示例:
class stone
{
public:
stone(int w, int h, int we)
:_w(w),_h(h),_weight(we)
{}
bool operator< (const stone& rhs) const
{return _weight <rhs._weight; }
private:
int _w,_h,_weight;
};
stone r1(2,3),r2(3,3).r3;
r3=min(r1,r2);
T只是一个符号,换成什么都可以。
相比类模板,函数模板不需要指明像complex<int>,编译器会进行实参推倒(argument deduction)。
在运行min函数的时候,编译器会去找stone这个类,看看类内是否能够让这两个能够比较,看到了operator<这个操作符
重载,于是编译器调用<这个符号。
如果stone没有进行操作符重载小于这个符号,那么编译器就会报出<这个符号没有定义。