C Primer Plus 例項化與具體化

2021-08-21 06:55:42 字數 2257 閱讀 3641

template void swap(t& a, t& b); //< 函式模板

void main()

template void swap(t& a, t& b)

template //< 函式模板

void swap(t& a, t& b);

template void swap(int &, int&); //< 使用swap模板顯示地生成int型別函式定義

void main()

template void swap(t& a, t& b)

到此產生了乙個疑問,顯示例項化有什麼用呢?其實可以總結下二者的區別:

隱式例項化:後面有程式用了,編譯器才會根據模板生成乙個例項函式;

顯式例項化:是無論是否有程式用,編譯器都會生成乙個例項函式;

template<> void swap(int &c1, int &c2);

template<> void swap(int &c1, int &c2);

意思就是,「不要使用swap模板來生成函式定義,使用專門為int型別顯示定義的函式定義」。

如下程式使用顯示具體化完成swap的特殊形式,即交換兩個元素的一部分內容:

struct job

; void show(job& j);

template //< 函式模板

void swap(t& a, t& b);

template void swap(int &, int&); //< 使用swap模板顯示地生成int型別函式定義

template<> void swap(job& j1, job& j2);//< 顯示具體化,特化swap模板

//< or

//template<> void swap(job& j1, job& j2);//< 顯示具體化,特化swap模板

void main()

; job sidney = ;

swap(sue, sidney); //< 使用顯示具體化

show(sue); //< susan:$7800 on floor:5

show(sidney); //< sidey:$7300 on floor:7

} template void swap(t& a, t& b) //常規模板

template<> void swap(job& j1, job& j2) //< 顯示具體化

void show(job& j)

至此已經出現了顯示例項化,隱式例項化,顯示具體化,非模板函式(即普通函式),那麼在函式呼叫時,是如何選取哪個函式版本呢?答案是:

具體化優先於常規模板,非模板函式優先於具體化和常規模板。

同時,顯示例項化,隱式例項化,顯示具體化統稱為具體化。

struct job

;void show(job& j);

template //< 函式模板

void swap(t& a, t& b);

template void swap(int &, int&); //< 使用swap模板顯示地生成int型別函式定義 顯示例項化

template<> void swap(job& j1, job& j2);//< 顯示具體化,特化swap模板

//< or

//template<> void swap(job& j1, job& j2);//< 顯示具體化,特化swap模板

void swap(float c1, float c2); //< 非模板函式

void main()

; job sidney = ;

swap(sue, sidney); //< 使用顯示具體化

show(sue); //< susan:$7800 on floor:5

show(sidney); //< sidey:$7300 on floor:7

cin.get();

}void swap(float c1, float c2)//< 非模板函式

template void swap(t& a, t& b) //常規模板

template<> void swap(job& j1, job& j2) //< 顯示具體化

void show(job& j)

Guice與例項化

guice 與例項化 class test1 class test2 class test2 guice有兩種例項化方法 生成單例,用於注射 inject protected void configure 直接 inject,inject private pgadmindao pgadmindao ...

Guice與例項化

guice 與例項化 class test1 class test2 class test2 guice有兩種例項化方法 生成單例,用於注射 inject protected void configure 直接 inject,inject private pgadmindao pgadmindao ...

JavaEE Bean例項化 例項工廠例項化

還有一種例項化bean的方式是採用是例項工廠,此種方式的工廠類中不再使用靜態方法建立bean例項,而是採用直接建立bean例項的方式,同時在配置檔案中,需要例項化的bean也並不是通過ckass屬性直接指向的例項化類,而是通過factory bean屬性指向配置的例項化工廠,然後使用factory ...