Name Lookup

Templates introduce a new wrinkle to name lookup. (See Chapter 2 for the non-template rules of name lookup.) When compiling a template, the compiler distinguishes between names that depend on the template parameters (called dependent names) and those that do not (nondependent names). Nondependent names are looked up normally when the template is declared. Dependent names, on the other hand, must wait until the template is instantiated, when the template arguments are bound to the parameters. Only then can the compiler know what those names truly mean. This is sometimes known as two-phase lookup .

Dependent Names

This section describes dependent names, and the following section describes what the compiler does with them.

A dependent name can have different meanings in different template instantiations. In particular, a function is dependent if any of its arguments are type-dependent. An operator has a dependent name if any of its operands are type-dependent.

A dependent type is a type that that can change meaning if a template parameter changes. The following are dependent types:

  • The name of a type template parameter or template template parameter:

    template<typename T> struct demo {T dependent; }
  • A template instance with template arguments that are dependent:

    template<typename T> class templ {};
    template<typename U> class demo {templ<U> dependent; }
  • A nested class in a dependent class template (such as the class template that contains the nested class):

    template<typename T> class ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.