C++模板編程 - 第五章 技巧性基礎知識

來源:互聯網
上載者:User

標籤:

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++模板編程 - 第五章 技巧性基礎知識

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.