函数模板(Function Template)

刚刚看完函数模板(Function Template),感觉这种方法不错,先总结如下,望各位多多指点

当函数重载时,为每一个函数写定义代码的是一件很繁琐的事,有了函数模板可就轻松多啦!

举个例子(max()函数是求一个数组中的最大数)

You can define a template for the function max() as follows:
template<class T> T max(T x[], int len)
{
     T max = x[0];
     for(int i = 1; i < len; i++)
     if(max < x[i])
     max = x[i];
     return max;
}

上面的那个class也可以换成typename,T代表着不同的数据类型,每次调用函数时都用原来的类型代替T

下面我们来看一个完整的例子

#include <iostream>
using std::cout;
using std::endl;
// Template for function to compute the maximum element of an array
template<typename T> T max(T x[], int len)
{
    T max = x[0];
    for(int i = 1; i < len; i++)
    if(max < x[i])
    max = x[i];
    return max;
}
int main(void)
{
    int small[] = { 1, 24, 34, 22};
    long medium[] = { 23, 245, 123, 1, 234, 2345};
    double large[] = { 23.0, 1.4, 2.456, 345.5, 12.0, 21.0};
    int lensmall = sizeof small/sizeof small[0];
    int lenmedium = sizeof medium/sizeof medium[0];
    int lenlarge = sizeof large/sizeof large[0];
    cout << endl << max(small, lensmall);
    cout << endl << max(medium, lenmedium);
    cout << endl << max(large, lenlarge);
    cout << endl;
    return 0;
}

输出结果如下:

    34
    2345
    345.5

 

Note that using a template doesn’t reduce the size of your compiled program in any way. The compiler generates a version of the source code for each function that you require. In fact, using templates can generally increase the size of your program, as functions can be created automatically even though an existing version might satisfactorily be used by casting the argument accordingly.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值