標籤:
Keyword Typename
1 template<typename T>2 class SomeClass3 {4 typename T::subtype * ptr;5 };
如果沒有typename,T::subtype會被認為是一個靜態成員。
A practical example:
1 // print elements in a STL container 2 template<typename T> 3 void print(T const & con) 4 { 5 typename T::const_iterator pos; 6 typename T::const_iterator end(con.end()); 7 8 for(pos=con.begin(); pos!=end; pos++) 9 ....10 }
如果身處於模板之中,想要調用另外一個模板函數,可能需要用到.template
1 template<int N>2 void printBitset(std::bitset<N> const & bs)3 {4 std::cout<<bs.template to_string<char, char_traits<char>, allocator<char> >(); // here we are inside a template and calling a template function5 }
在5.2節,書上的說法和我的運行結果出現了分歧,我的運行環境是vs2013。
1 #include<iostream> 2 3 using namespace std; 4 5 void foo() 6 { 7 cout << "global foo" << endl; 8 } 9 10 template<typename T>11 class Base{12 public:13 void foo()14 {15 cout << "foo in Base" << endl;16 }17 };18 19 template<typename T>20 class Derived1 :Base < T >21 {22 public:23 void goo()24 {25 foo(); // foo in Base26 Base<T>::foo(); // foo in Base27 ::foo(); // global foo28 }29 };30 31 int main()32 {33 Derived1<int> d1;34 d1.goo();35 return 0;36 }
書上的說法是goo中第一個foo調用實際調用的並不是Base中的foo,然而我的運行結果把書上寫的否定了。所以說這個事情可能是和編譯環境有關係。為了避免不確定性,還是加上Base<T>::首碼,或者使用this指標比較保險,能夠避免不確定性。
changlog:
2015/6/18 要滾去看數理方程了,先寫這麼多。
C++模板編程 - 第五章 技巧性基礎知識