Function template instances
C++编译器并不直接编译template函数。编译器遇到template函数调用后,会复制一份template函数并把占位符类型替换成真正的数据类型。拥有真正数据类型的函数称为function template instance。
template <typename Type> // this is the template parameter declaration
Type max(Type tX, Type tY)
{
return (tX > tY) ? tX : tY;
}
当编译这个程序,编译器遇到该函数的调用:
int nValue = max(3, 7); // calls max(int, int)
编译器就会创建一个function template instance
int max(int tX, int tY)
{
return (tX > tY) ? tX : tY;
}
这个实例就是一个普通的可编译函数了。
值得一提的是编译器是则可以知道为每一种占位符类型组合只创建一个实例。如果你的template函数没有被调用,那就不会有任何实例被创建。
Operators, function calls, and function templates
首先,我们创建一个简单的类
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents)
: m_nCents(nCents)
{
}
};
然后我们试着调用我们的templated max() 函数。
Cents cNickle(5);
Cents cDime(10);
Cents cBigger = max(cNickle, cDime);
C++会创建一个temple实例
Cents max(Cents tX, Cents tY)
{
return (tX > tY) ? tX : tY;
}
然后,C++就开始编译这个函数,但是显而易见的是,C++不知道怎么来判断tX > tY。
要想解决这个问题,我们需要重载 > 操作符:
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents)
: m_nCents(nCents)
{
}
friend bool operator>(Cents &c1, Cents&c2)
{
return (c1.m_nCents > c2.m_nCents) ? true: false;
}
};