Name binding and dependent names (C++ only)

Name binding is the process of finding the declaration for each name that is explicitly or implicitly used in a template. The compiler may bind a name in the definition of a template, or it may bind a name at the instantiation of a template.

A dependent name is a name that depends on the type or the value of a template parameter. For example:

template<class T> class U : A<T>
{
  typename T::B x;
  void f(A<T>& y)
  {
    *y++;
  }
};      

The dependent names in this example are the base class A<T>, the type name T::B, and the variable y.

The compiler binds dependent names when a template is instantiated. The compiler binds non-dependent names when a template is defined. For example:

void f(double) { cout << "Function f(double)" << endl; }

template<class T> void g(T a) {
  f(123);
  h(a);
}

void f(int) { cout << "Function f(int)" << endl; }
void h(double) { cout << "Function h(double)" << endl; }

void i() {
  extern void h(int);
  g<int>(234);
}

void h(int) { cout << "Function h(int)" << endl; }

The following is the output if you call function i():

Function f(double)
Function h(double)

The point of definition of a template is located immediately before its definition. In this example, the point of definition of the function template g(T) is located immediately before the keyword template. Because the function call f(123) does not depend on a template argument, the compiler will consider names declared before the definition of function template g(T). Therefore, the call f(123) will call f(double). Although f(int) is a better match, it is not in scope at the point of definition of g(T).

The point of instantiation of a template is located immediately before the declaration that encloses its use. In this example, the point of instantiation of the call to g<int>(234) is located immediately before i(). Because the function call h(a) depends on a template argument, the compiler will consider names declared before the instantiation of function template g(T). Therefore, the call h(a) will call h(double). It will not consider h(int), because this function was not in scope at the point of instantiation of g<int>(234).

Point of instantiation binding implies the following:

Related information