實例化和具體化詳解

primer Plus在解釋具體化和實例化看的有點亂,分解出來備忘ios

在代碼中包含函數模板自己並不會生成函數定義,它只是用於生成函數定義的方案c++

編譯器使用模板爲我寫類型生成函數定義時,獲得的是模板實例app

如這個模板ide

template<typename T>
void Swap(T &t1,T &t2)
{
    T _t;
    _t=t1;    
    t1=t2;
    t2=_t;
}

調用函數

    int i = 10,j=20;
    ::cout<<"i, j ="<<i<<" , "<<j<<endl;
    cout<<" Using compiler -generated int swapper:\n";
    Swap(i,j);
    ::cout<<"Now i, j ="<<i<<" , "<<j<<endl;

調用 Swap(i,j)致使編譯器生成Swap()的一個實例,該實例使用int類型。模板並不是函數定義,但使用int的模板實例是函數定義。
這種實例化方式被稱爲隱式實例化,編譯器之因此知道須要進行定義,是因爲程序調用Swap()函數時提供了int 參數。spa

c++還容許顯示實例化code

其語法是,聲明所需的種類用<>指示類型並在聲明前加上template:blog

template void Swap<int>(int &t1,int &t2);

例子ci

#include<iostream>
using namespace std;

template<typename T>
void Swap(T &t1,T &t2);

template void Swap<int>(int &t1,int &t2);

int main()
{
    cout<<" Using compiler -generated int swapper:\n";
    int i = 10,j=20;
    cout<<"i, j ="<<i<<" , "<<j<<endl;    
    cout<<" Using compiler -generated int swapper:\n";
    Swap(i,j);
    cout<<"Now i, j ="<<i<<" , "<<j<<endl;    
    cin.get();
}

template<typename T>
void Swap(T &t1,T &t2)
{
    T _t;
    _t=t1;    
    t1=t2;
    t2=_t;
}


顯示具體化的原型和定義應以template<>打頭,並經過名稱來指出類型。get

顯式具體化優先於常規模板,而非模板函數優先於具體化和常規模板

與顯式實例化不一樣的是,顯式具體化使用下面的聲明方式 ,兩種方式是同樣的

template<> void Swap<job>(job &c1,job &c2);
template<> void Swap(job &c1,job &c2);

這們的意思是不要使用Swap()模板來生成函數定義,而使用專門的job類型顯式地定義函數定義
顯式具體化聲明在關鍵字template 後加<>,顯式實例化沒有

具體化小例子

#include<iostream>
using namespace std;

struct job
{
    char name[40];
    double salary;
    int floor;
};
template<typename T>
void Swap(T &t1,T &t2);
template<> void Swap<job>(job &c1,job &c2);

void show(job j);
int main()
{
    

    job sue={"Suan Yaffee",73000.123,7};
    job sidey={"Sidney Taffee",78060.1,2};
    cout<<"sue:\n";
    show(sue);
    cout<<"sidey:\n";
    show(sidey);
    Swap(sue,sidey);
    cout<<"sue:\n";
    show(sue);
    cout<<"sidey:\n";
    show(sidey);
    cin.get();
}

template<typename T>
void Swap(T &t1,T &t2)
{
    T _t;
    _t=t1;    
    t1=t2;
    t2=_t;
}

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)
{
    cout<<"name :"<<j.name<<"  salary:  "<<j.salary<<" floor :  "<<j.floor<<endl;
}
相關文章
相關標籤/搜索