第16章 模板與泛型程式設計 4

2022-09-23 19:45:11 字數 619 閱讀 2377

16.1.5 非型別模板形參

在呼叫函式時,非型別形參將用值代替,值的型別在模板形參表中指定。

template 

void array_init(t (¶m)[n]) 

} template

void array_init(t (¶m)[n])

}int i=; 

array_init(i); 

int i=;

array_init(i);模板非型別形參是模板定義內部的常量值,在需要常量表示式的時候,可使用非型別形參(就像這裡所做的一樣)指定陣列的長度。

型別等價性與非型別形參

對模板的非型別形參而言,求值結果相同的表示式被認為是等價的。

在函式模板內部完成的操作限制了可用於例項化該函式的型別。程式設計師的責任是,保證用作函式實參的型別實際上支援所用的任意操作,以及保證在模板使用那些操作的環境中那些操作執行正常。

編寫模板**時,對實參型別的要求盡可能少是很有益的。

雖然簡單,但它說明了編寫泛型**的兩個重要原則:

模板的形參是const引用。

函式體中的測試只用比較。

通過將形參設為const引用,就可以允許使用不允許複製的型別。

摘自 xufei96的專欄

第16章 模板與泛型程式設計 10

16.4.4 queue和queueitem的友元宣告 1.將類模板設為友元 template class queueitem type item queueitem next friend class queue 2.queue輸出操作符 template ostream operator ost...

第16章 模板與泛型程式設計 13

16.5 乙個泛型控制代碼類 16.5.1 定義控制代碼類 ifndef handle h define handle h include stdafx.h include using namespace std templateclass handle t operator t operator ...

第16章 模板與泛型程式設計 15

16.6.2 類模板的特化 1.定義類特化 template class queue const string front const void push const char void pop bool empty const friend ostream operator ostream os,...