函数模板(二)

来源:互联网 发布:刚买的域名被墙 编辑:程序博客网 时间:2024/06/05 07:27

又到了我最喜欢的学习语言的时间了 好开心啊!!!

显式具体化:struct job{    char name[40];    double salary;    int floor;};***C++允许将一个结构赋给另一个结构。第三代具体化:*对于给定的函数名,可以有非模板函数,模板函数和显式具体化模板函数以及他们的重载版本。*显式具体化的原型和定义应以template<>打头,并通过名称来指出类型。*具体化将覆盖常规模板,而非模板函数将覆盖具体化和常规模板。下面是用于交换job结构的非模板函数,模板函数和具体化的原型:///non_template function prototypevoid Swap(job &, job &);///template prototypetemplate<class Any>void Swap(Any &, Any &);///explicit specialization for the job typetemplate <> void Swap<job>(job &, job &);若有多个原型,非模板版本将优先于显式具体化和模板版本,而显式具体化将优先于使用模板生成的版本。例如,在下面的代码中,第一次调用Swap()时使用通用版本,而第二次使用基于job类型的显式具体化版本。template<class Any>void Swap(Any &, Any &);///explicit specialization for the job typetemplate <> void Swap<job>(job &, job &)int main(){    double u, v;    ...    Swap(u, v);    job a, b;    ...    Swap(a, b);}Swap<job>中的<job>是可选的,因为函数的参数类型表明,这是job的一个具体化。该原型也可这样写:template <> void Swap(job &, job &);*****************************************************************************************************                       yomi自制  :  华丽的分割线*****************************************************************************************************看个小程序吧:#include<iostream>using namespace std;template <class Any>void Swap(Any &a, Any & b);struct job{    char name[40];    double salary;    int floor;};template <> void Swap<job> (job &j1, job &j2);void Show(job &j);int main(){    cout.precision(2);    cout.setf(ios:: fixed, ios:: floatfield);    int i=10,j = 20;    cout << "i, j = " << i << ", " << j << ".\n";    cout << "Using compiler_generated int swapper: \n";    Swap(i, j);    cout << "Now i, j = " << i << ", " << j << ".\n";    job sue = {"Susan Yaffee", 73000.606, 7};    job sidney = {"Sidney Taffee", 78060.726, 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 <class Any>void Swap(Any &a, Any &b){    Any temp;    temp = a;    a = b;    b = temp;}/// swap just salary and floor fields of a job structuretemplate <> 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){    cout << j.name << ": $" << j.salary << " on floor " << j.floor << endl;}/*i, j = 10, 20.Using compiler_generated int swapper:Now i, j = 20, 10.Before job swapping:Susan Yaffee: $73000.61 on floor 7Sidney Taffee: $78060.73 on floor 9After job swapping:Susan Yaffee: $78060.73 on floor 9Sidney Taffee: $73000.61 on floor 7Process returned 0 (0x0)   execution time : 5.840 sPress any key to continue.*/ok , 今天对于C++的学习到此结束。 最近为了准备省赛都没怎么学C++, 不开森!!! 不管怎么说,我会尽量抽时间的。


0 0