C++之函数模板

其实关于函数模板自己已经看了很多次了,只是实在太菜,用的很少以至于总是给忘了,现在简单记下来。
函数模板是通用的函数描述,其通过将类型作为参数传递给模板,可使编译器生成该类型的函数。
一个简单的函数模板例程:

#include <iostream>

using namespace std;

template <typename T>
void Swap(T &a, T &b);

int main()
{
    int i = 10;
    int j = 20;
    cout << "i, j = " << i << ", " << j << endl;
    Swap(i, j);
    cout << "Now i, j = " << i << ", " << j << endl;

    double x = 24.5;
    double y = 87.1;
    cout << "x, y = " << x << ", " << y << endl;
    Swap(x, y);
    cout << "Now x, y = " << x << ", " << y << endl;

    return 0;
}

template <typename T> 
void Swap(T &a, T &b)
{
    T temp;
    temp = a;
    a = b;
    b = temp;
}

需要多个对不同类型使用同一种算法的函数时,可以通过类似上面程序的模板。但并非所有的类型都使用相同的算法,这时就可以像重载常规函数定义一样重载模板定义。和常规重载一样,被重载的模板的函数特征标必须不同。

#include <iostream> 

template <typename T>
void Swap(T &a, T &b);

template <typename T>
void Swap(T *a, T *b, int n);

void Show(int a[]);

const int Lim = 8;

int main()
{
    using namespace std;
    int i = 10, j = 20;
    cout << "i, j = " << i << ", " << j << endl;
    cout << "Using complier-generated int swapper: \n";
    Swap(i, j);
    cout << "Now i, j = " << i << ", " << j << endl;

    int d1[Lim] = {0, 7, 0, 4, 1, 7, 7, 6};
    int d2[Lim] = {0, 7, 2, 0, 1, 9, 6, 9};
    cout << "Original arrays:\n";
    Show(d1);
    Show(d2);
    Swap(d1, d2, Lim);
    cout << "Swapped arrays: \n";
    Show(d1);
    Show(d2);

    return 0;
}

template <typename T>
void Swap(T &a, T &b)
{
    T temp;
    temp = a;
    a = b;
    b = temp;
}

template <typename T>
void Swap(T *a, T *b, int n)
{
    T temp;
    for (int i = 0; i < n; i++)
    {
        temp = a[i];
        a[i] = b[i];
        b[i] = temp;
    }
}

void Show(int a[])
{
    using namespace std;
    cout << a[0] << a[1] << "/";
    cout << a[2] << a[3] << "/";
    for (int i = 4; i < Lim; i++)
    {
        cout << a[i];
    }
    cout << endl;
}

【参考】:C++ Primer Plus

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值