泛型编程::函数模板及其重载、实例化和具体化

来源:互联网 发布:js 读取数字证书 编辑:程序博客网 时间:2024/05/08 13:10

最基本的函数模板:

#include <iostream>

using namespace std;                      


template <typename T>                    //同样可以使用 class T
void Swap(T & a, T & b);


int main()
{
int i = 20, j = 40;
cout << "Before changed: i = " << i
  << " j = " << j << endl;
Swap(i, j);
cout << "After changed: i = " << i
<< " j = " << j << endl;


system("pause");
return 0;
}


template <typename T>
void Swap(T & a, T & b)
{
T 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);


template <typename T>
void show(T * a, int i);




int main()
{
int i = 10, j = 30;
cout << "Before changed: i = " << i
<< ", j = " << j<<endl;
Swap(i, j);
cout << "After changed: i = " << i
<< ", j = " << j<<endl;


int a[5] = { 5, 9, 8, 2, 1 };
int b[5] = { 6, 3, 2, 4, 1 };
cout << "Before changed:"<<endl;
show(a, 5);
show(b, 5);
Swap(a, b, 5);
cout << "After changed:" << endl;
show(a, 5);
show(b, 5);


system("pause");
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)
{
for (int i = 0; i < n; i++)
{
T temp;
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}


template <typename T>
void show(T * a, int n)
{
for (int i = 0; i < n; i++)
{
cout << *(a + i)<< " ";
}
cout << endl;
}

显式具体化

有如下结构:
struct job
{
char name[40];
double salary;
int floor;
};
如果仅想交换salary和floor成员,则需使用其他代码,但是Swap()参数保持不变,因此无法使用模板重载来提供其他的代码。
然而可以提供一个具体化函数定义,称为显式具体化:
  • 对于给定的函数名,可以有非模板函数、模板函数和显式具体化模板函数及其他重载版本。
  • 显式具体化的原型和定义以template<>大头,并通过名称指出其类型。
  • 具体化优先于常规模板,而非模板函数优先于具体化和常规模板。
template <> void Swap<job>(job &,job &); 其中<job>是可选择的。
原创粉丝点击