码迷,mamicode.com
首页 > 编程语言 > 详细

C++函数模板

时间:2016-07-07 22:36:39      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:

C++函数模板允许以任意类型的方式来定义函数。例如,可以这样建立一个交换模板:

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

在标准C++98添加关键字typename之前,C++使用关键字class来创建模板。也就是说,可以这样编写模板定义:

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

需要多个对不同类型使用同一种算法的函数时,可使用模板。然而,并非所有的类型都使用相同的算法,为满足这种需求,可以像重载常规函数定义那样冲在模板定义。和常规重载一样,被重载的模板的函数特征必须不同。

下面的例程中新增了一个交换模板,用于交换两个数组中的元素。

#include <iostream>
using namespace std;
template <typename T>
void Swap(T &a, T &b);

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

void Show(int a[]);
int main() {
    int x = 1, y = 2;
    Swap(x, y);
    cout << x << "\t" << y << endl;
    int a[10], b[10], n = 10;
    for (int i = 0; i < 10; i ++)
        a[i] = i + 1, b[i] = 10 - i;
    Swap(a, b, 10);
    Show(a);
    Show(b);
    return 0;
}

template <typename T>
void Swap(T &a, T &b) {
    T 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[]) {
    for (int i = 0; i < 10; i ++)
        cout << a[i] << " ";
    cout << endl;
}

输出效果:

2   1
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10

显式具体化

实例(实际运行有错误,可能是编译器版本问题):

#include <iostream>
using namespace std;
template <typename T>
void Swap(T &a, T &b);

struct job
{
    char name[40];
    double salary;
    int floor;
};

// explicit specialization
template <> void Swap<job>(job &j1, &j2);
void Show(job &j);

int main() {
    int a = 1, b = 2;
    Swap(a, b);
    cout << a << "\t" << b << endl;
    job j1 {"moon", 3000.3, 2};
    job j2 {"lit", 2000.2, 1};
    Swap(j1, j2);
    Show(j1);
    Show(j2);
    return 0;
}

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

template <> void Swap<job>(job &j1, job &j2)
{
    double t1;
    t1 = j1.salary;
    j1.salary = j2.salary;
    j2.salary = t1;
    int t2;
    t2 = j1.floor;
    j1.floor = j2.floor;
    j2.floor = t2;
}

void Show(Job &j) {
    cout << j.name << "\t" << j.salary << "\t" << j.floor << endl;
}

这里提示:template <> void Swap<job>(job &j1, &j2);出错。

实例化和具体化

。。。

C++函数模板

标签:

原文地址:http://www.cnblogs.com/moonlightpoet/p/5651702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!