C++ Primer 5th笔记(chap 16 模板和泛型编程)成员模板
生活随笔
收集整理的這篇文章主要介紹了
C++ Primer 5th笔记(chap 16 模板和泛型编程)成员模板
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 成員模板( member template)
一個類( 無論是普通類還是類模板) 可以包含本身是模板的成員函數。
- 成員模板不能是虛函數。
1.1 普通( 非模板 ) 類的成員模板
/ / 函數對象類, 對給定指針執行 delete class DebugDelete { public:DebugDelete (std:rostream &s = std::cerr ): os (s) { }/ / 與任何函數模板相同, T 的類型由編譯器推斷template <typename T> void operator ( ) (T *p) const{ os ? "deleting unique_ptr" ? std::endl; delete p;}private:std::ostream &os; } double* p new double; DebugDelete d; / / 可像 delete 表達式一樣使用的對象 d (p); / / 調用 DebugDelete::operator ( ) (double* ) , 釋放 pint* ip; // 在一個臨時 DebugDelete 對象上調用 operator ( ) (int*) DebugDelete ( ) (ip);/ / 銷 毀 p 指向的對象 //實例化 DebugDelete::operator ( > <int> (int * ) unique_ptr<int, DebugDelete> p (new int, DebugDelete ( ) );// 銷 毀 sp 指向的對象 / / 實例化 DebugDelete::operator ( ) <string> (string* ) unique_ptr<string, DebugDelete> sp (new string, DebugDelete ( ) );/ / DebugDelete 的成員模板實例化樣例 void DebugDelete::operator ( ) (int *p) const { delete p; } void DebugDelete::operator ( ) (string *p) const { delete p; }1.2 類模板的成員模板
類模板也可以有成員模板,此時類和成員各自有自己的、獨立的模板參數。
template <typename T> class Blob {template <typename It> Blob (It b, It e);//.. . }與類模板的普通函數成員不同, 成員模板是函數模板。
當我們在類模板外定義一個成員模板時, 必須同時為類模板和成員模板提供模板參數列表。 類模板的參數列表在前, 后跟成員自己的模板參數列表:
//定義一個類模板的成員, 類模板有一個模板類型參數, 命名為 T。 // 而成員自身是一個函數模板, 它有一個名為 It 的類型參數。template <typename T>//類的類型參數 //構造函數的類型參數 template <typename It> Blob<T>::Blob (It b, It e):data (std::make_shared<std::vector<T?(b, e) ) { }1.3 實例化與成員模板
為了實例化一個類模板的成員模板, 我們必須同時提供類和函數模板的實參。
int ia[] = {0,1,2,3,4,5,6, 7,8,9}; vector<long> vi = {0,1,2,3,4,5,6, 7,8,9}; list<const char*> w = {"now", "is", "the", "time" };// 實例化 Blob<int>類及其接受兩個 int*參數的構造函數 Blob<int> al (begin (ia) , end (ia) );// 實 例 化 Blob<int>類的接受兩個 vector<long>::iterator 的構造函數 Blob<int> a2 (vi.begin ( ), vi.end ( ) );// 實例化Blob<string>及其接受兩個list<const char*〉: : iterator 參數的構造函數 Blob<string> a3 ( w.begin ( ), w.end ( ) );總結
以上是生活随笔為你收集整理的C++ Primer 5th笔记(chap 16 模板和泛型编程)成员模板的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(cha
- 下一篇: C++ Primer 5th笔记(cha