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