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

C++之函数模板

2017-09-15 15:58 218 查看
其实关于函数模板自己已经看了很多次了,只是实在太菜,用的很少以至于总是给忘了,现在简单记下来。

函数模板是通用的函数描述,其通过将类型作为参数传递给模板,可使编译器生成该类型的函数。

一个简单的函数模板例程:

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数模板 c++