看一下自定義類型如何在函數頭傳回類定義的類型:
一個vec初略模闆:
要實作erase函數,傳回值為iterator,下面的函數定義可以嗎?
上面的是錯誤的,應該在
為什麼要加typename,因為iterator這個類型是在Vec<T>類定義的。C++規定:無論何時,如果使用了一個依賴與模闆參數的類型時(如vector<T>),而且你想要使用這個類型的成員函數(如size_type)本身就是一個類型,就必須在整個名字前加上typename。
上面的typename告訴系統:vector<T>::size_type 是一個類型的名字,雖然系統并不知道類型T是什麼,無論什麼時候,如何你使用一個依賴于模闆參數的類型時,比如vector<T>,而且 你想要使用這個類型的成員時,比如size_type,它本身也是一個類型時,你必須在整個名字之前加上typename,以便讓系統知道要把這個名字當成類型來對待。
msdn解釋:
The typename keyword tells the compiler that an unknown identifier is a type.
Use this keyword only in template definitions. For example:
This keyword can also be used in place of class in template parameter lists. For example, the following statements are identical:
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fkeyword_typename.htm