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

c++函数模板

2015-12-21 18:54 357 查看
资料摘自《C++ Primer Plus》

模板定义

#include <iostream>

template<class T>

void Swap(T &a, T &b) {

T temp = a;

a = b;

b = temp;

}

int main() {

using namespace std;

int i = 10;

int j = 20;

Swap(i, j);

cout << i << "," << j << endl;

double x = 23.5;

double y = 22.6;

Swap(x, y);

cout << x << "," << y << endl;

return 0;

}

上面示例,Swap()将生成int与double两个版本。

函数模板不能缩短可执行程序,最终仍将由两个独立的函数定义,就像以手工方式定义了这些函数一样。最终的代码不包含任何模板,而只包含了为程序生成的实际函数。

重载模板

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

#include <iostream>

template<class T>

void Swap(T &a, T &b) {

T temp = a;

a = b;

b = temp;

}

template<class 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[]) {

std::cout << a[0] << "," << a[1] << "," << a[2] << std::endl;

}

int main() {

using namespace std;

int i = 10;

int j = 20;

Swap(i, j);

cout << i << "," << j << endl;

double x = 23.5;

double y = 22.6;

Swap(x, y);

cout << x << "," << y << endl;

int aa[3] = { 1, 2, 3 };

int bb[3] = { 4, 5, 6 };

Swap(aa, bb, 3);

show(aa);

show(bb);

return 0;

}

模板的局限性

假设有如下模板函数:

template<class T>

void f(T a, T b) {

...

a = b;

...

}

但如果T为数组,则示例中的a = b将不成立。

即编写的模板函数很可能无法处理某些类型。这时可为特定的类型提供具体化的模板定义。假设定义了如下结构:

#include <iostream>

struct job {

char name[40];

double salary;

int floor;

};

template<class T>

void Swap(T &a, T &b) {

T temp = a;

a = b;

b = temp;

}

template<>

void Swap<job>(job &a, job &b) { //显式具体化

double t1 = a.salary;

int t2 = a.floor;

a.salary = b.salary;

a.floor = b.floor;

b.salary = t1;

b.floor = t2;

}

void show(const job &a) {

cout << a.name << "," << a.salary << "," << a.floor << endl;

}

int main() {

using namespace std;

int i = 10;

int j = 20;

Swap(i, j);

cout << i << "," << j << endl;

double x = 23.5;

double y = 22.6;

Swap(x, y);

cout << x << "," << y << endl;

job sue = {"Susan", 73000.60, 7};

job sidney = {"Sidney", 78060.72, 9};

Swap(sue, sidney);

show(sue);

show(sidney);

return 0;

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