您的位置:首页 > 编程语言 > C语言/C++

C++函数模板

2016-07-07 21:50 309 查看
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);出错。

实例化和具体化

。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: