c++为什么存在显式实例化,显式具体化两种显式声明

2025-05-14 00:38:24
推荐回答(1个)
回答(1):

1>显式具体化
显式具体化也是基于函数模板的,只不过在函数模板的基础上,添加一个专门针对特定类型的、实现方式不同的具体化函数。

[cpp] view plain copy

  • template<>void swap(job &a, job &b)  

  • {  

  • int salary;  

  • salary = a.salary;  

  • a.salary = b.salary;  

  • b.salary = salary;  

  • }  



  • 如上所示,该具体化函数的实现与模板并不一致,编译器解析函数调用时会选择最匹配的函数定义。

    2>定义同名常规函数

    [cpp] view plain copy

  • void swap(job &a, job &b)  

  • {  

  • int salary;  

  • salary = a.salary;  

  • a.salary = b.salary;  

  • b.salary = salary;  

  • }  


  • 由于编译器在重载解析时,会选择最匹配函数定义,所以在调用swap(jobA, jobB)时,编译器会选择void swap(job &a, job &b)函数定义,而屏蔽了模板函数。

    同时,模板函数也可以重载,其操作与常规函数一致。

    [cpp] view plain copy

  • template  void swap(T &a, T &b);  

  • template  void swap(T &a, T &b, T &c);  

  • template  void swap(T &a, T &b)  

  • {  

  • T temp;  

  • temp = a;  

  • a = b;  

  • b = temp;  

  • }  

  • template  void swap(T &a, T &b, T &c)  

  • {  

  • T temp;  

  • temp = a;  

  • a = b;  

  • b = c;  

  • c = temp;  

  • }  

  • 上面主要说的是函数模板的具体化,下面说下模板实例化。

    函数模板:

    [cpp] view plain copy

  • #define MAXNAME 128  

  • struct job  

  • {  

  • char name[MAXNAME]:  

  • int salary;  

  • };  

  • template  

  • void swap(T &a, T &b )  

  • {  

  • T temp;  

  • temp = a;  

  • a = b;  

  • b = temp;  

  • };  

  • template void swap(int &a, int & b);  //显式实例化,只需声明  

  • template<> void swap(job &a, job &b)   //显式具体化(上面已经讲过,注意与实例化区分开,必须有定义)  

  • {  

  • int salary:  

  • salary = a.salary:  

  • a.salary = b.salary;  

  • b.salary = salary;  

  • };//explicite specialization.  


  • 类模板:

    [cpp] view plain copy

  • template   

  • class Arrary  

  • {  

  • private:  

  • T* ar;  

  • int l;  

  • ...  

  • };//template class declaration.  

  • template class Array;   //explicit instantiation. 显式实例化  

  • template<> class Array  

  • {  

  • private:  

  • job* ar;  

  • int l;  

  • };//expicit specialization.   显式具体化,类定义体可以不同于类模板Array  



  • 相应的,隐式实例化指的是:在使用模板之前,编译器不生成模板的声明和定义实例。只有当使用模板时,编译器才根据模板定义生成相应类型的实例。如:
    int i=0, j=1;
    swap(i, j);  //编译器根据参数i,j的类型隐式地生成swap(int &a, int &b)的函数定义。
    Array arVal;//编译器根据类型参数隐式地生成Array类声明和类函数定义。

    显式实例化:
    当显式实例化模板时,在使用模板之前,编译器根据显式实例化指定的类型生成模板实例。如前面显示实例化(explicit instantiation)模板函数和模板类。其格式为:
    template typename function(argulist);
    template class classname;
    显式实例化只需声明,不需要重新定义。编译器根据模板实现实例声明和实例定义。

    显示具体化:
    对于某些特殊类型,可能不适合模板实现,需要重新定义实现,此时可以使用显示具体化(explicite specialization)。显示实例化需重新定义。格式为:
    template<> typename function(argu_list){...};
    template<> class classname{...};

    综上:

    template<> void swap(job &a, job &b) {……};是函数模板的显式具体化,意思是job类型不适用于函数模板swap的定义,因此通过这个显式具体化重新定义;也可简写作template<> void swap(job &a, job &b);

    template void swap(job &a, job &b);是函数模板的一个显式实例化,只需声明,编译器遇到这种显式实例化,会根据原模板的定义及该声明直接生成一个实例函数,该函数仅接受job型。否则编译器遇到模板的使用时才会隐式的生成相应的实例函数。