14.2 - Function template instances

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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值