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.』


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


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

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




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