C++ Templates讀書筆記 Tricky Basics

來源:互聯網
上載者:User

   C++ Templates讀書筆記< 二 > Tricky Basics

* 關鍵字typename,用來說明某個標誌符是個型別.

eg: 1         template < typename T >
2         class MyClass
3         {
4             typename T::SubType* ptr;
5             
6         };* assignment運算的template版本並不會取代default assignment運算* 雙重模板參數: Template Template Parameterseg: 1         template < typename T, 
 2                 template < typename ELEM
 3                            typename ALLOC = std::alloctator<ELEM> > 
 4                 class CONT = std::deque
 5                 >
 6         class Stack
 7         {
 8             COUT<T> elems;        // 以第一個參數的型別完成了執行個體化, 也可以利用class template內的任何型別 來執行個體化
10         };
11     // 註:template template arguments必須完全符合對應的參數。預設的template arguments會被編譯器忽略。
12     // 所以,如果上面沒有寫 typename ALLOC = std::alloctator<ELEM> 就會報錯function templates 不允許擁有template template parameters* 初始化eg: 1         template < typename T >
 2         class MyClass
 3         {
 4         private:
 5             T x;
 6         public:
 7             MyClass()
 8                 : x()    // 即使T為build-in type,x也可以被初始化
 9             {
10             }
11         };* 只有by value傳參時,才會發生 array to pointer 的轉換

eg:

 1 template < typename T >
 2         inline T const& max( T const& a, T const& b )
 3         {
 4             return a < b ? b : a;
 5         }
 6         
 7         max( "apple", "peach" );    // ok
 8         max( "apple", "tomato" );    // error, 型別不同,一個是char const[6],一個是char const[7]
 9         
10         template < typename T >
11         inline T max( T a, T b )
12         {
13             return a < b ? b : a;
14         }
15         
16         max( "apple", "peach" );    // ok
17         max( "apple", "tomato" );    // ok, 發生了array to pointer的轉換, 但比較結果是錯的,因為實際上比較的是指標地址


著作權聲明:本篇為原創文章,允許轉載,但轉載時請務必以超連結形式標明文章的原始出處和作者資訊。請尊重本人的勞動成果,謝謝!

小祥的BLOG http://xfxsworld.cnblogs.com 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.