Name Lookup in Class Templates

C++ Primer 4/e在Template Compilation Models這個地方有一個警告:『Compiling templates is a surprisingly difficult task. Fortunately, it is a task handled by compiler writers. Unfortunately, some of that complexity is pushed onto users of templates: Templates contain two kinds of names:

  1. Those that do not depend on a template parameter

  2. Those that do depend on a template parameter

It is up to the template designer to ensure that all names that do not depend on a template parameter are defined in the same scope as the template itself.

It is up to users of a template to ensure that declarations for all functions, types, and operators associated with the types used to instantiate the template are visible. This responsibility means that the user must ensure that these declarations are visible when a member of a class template or a function template is instantiated.

Both of these requirements are easily satisfied by well-structured programs that make appropriate use of headers. Authors of templates should provide a header that contains declarations for all the names used in the class template or in the definitions of its members. Before defining a template on a particular type or using a member of that template, the user must ensure that the header for the template type and the header that defines the type used as the element type are included.』

中文版的這樣寫:『編譯template是一件令人吃驚的困難工作。幸運的是這工作由編譯器撰寫者去處理。不幸的是有些複雜事物被推給了templates用戶。Templates內含兩種名稱:

  1. 與template參數無關的名稱
  2. 與template參數相關的名稱

「確保所有與template參數無關的名稱均被定義於與template本身相同的作用域中」是template設計者的責任。

「確保與template目標型別相關的所有函式、型別、運算子均可見」則是template使用者的責任。這個責任意味用戶必須確保在class template成員或function template被具現化時,前述各物的宣告均可見。

適當使用表頭檔、組織良好的程式能夠輕易滿足這兩個需求。Template作者應該提供一個表頭檔,內含class template或其成員定義式用到的所有名稱。當以某特定目標型別定義template,或使用template成員時,用戶必須確保template表頭檔和定義目標型別的表頭檔都被含入。』

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *