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表头档和定义目标型别的表头档都被含入。’