第三代具体化(ISO/ANSI C++标准)
- 给定函数名,可以由非模板函数、模板函数和显式具体化模板函数以及重载
- 显式具体化的原型和定义以 template<>开头,通过名称来指出类型
- 具体化优先于常规模板,非模板函数优于具体化和常规模板
举例:
-
//非模板函数
-
void Swap(job &, job &)
-
-
//模板函数
-
template <typename T>
-
void Swap(T &, T &)
-
-
//显式具体化模板函数
-
template <> void Swap<job> (job &, job &);
程序
-
// --8.13 模板,显示具体化实例
-
#include<iostream>
-
template <typename T>
-
void Swap(T &a, T &b);
-
-
//模板
-
struct job
-
{
-
char name[40];
-
double salary;
-
int floor;
-
};
-
-
//模板具体化实例
-
template <> void Swap<job>(job &j1, job & j2);
-
void Show(job &j);
-
-
int main()
-
{
-
using namespace std;
-
cout.precision(2);
-
cout.setf(ios::fixed, ios::floatfield);
-
int i = 10, j = 20;
-
cout << "i, j=" << i << ", " << j << ".\n";
-
cout << "使用模板 int" << endl;
-
Swap(i, j);
-
cout << "NOW i, j = " << i << ", " << j << ".\n";
-
-
job sue = { "Allen Blue", 100.15, 45 };
-
job sidney = { "Siney Tadf", 120.45, 9 };
-
cout << "Before job swapping:\n";
-
Show(sue);
-
Show(sidney);
-
Swap(sue, sidney);
-
cout << "After job swapping:\n";
-
Show(sue);
-
Show(sidney);
-
-
return 0;
-
-
}
-
-
template<typename T>
-
void Swap(T &a, T &b) //普通模式
-
{
-
T temp;
-
temp = a;
-
a = b;
-
b = temp;
-
}
-
-
//显式,并且只交换其中两个
-
template <> void Swap<job>(job &j1, job &j2)
-
{
-
double t1;
-
int t2;
-
t1 = j1.salary;
-
j1.salary = j2.salary;
-
j2.salary = t1;
-
t2 = j1.floor;
-
j1.floor = j2.floor;
-
j2.floor = t2;
-
}
-
-
void Show(job &j)
-
{
-
using namespace std;
-
cout << j.name << ": $ " << j.salary << " on floor " << j.floor << endl;
-
}
结果
文章来源: kings.blog.csdn.net,作者:人工智能博士,版权归原作者所有,如需转载,请联系作者。
原文链接:kings.blog.csdn.net/article/details/95348932