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.
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.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).
- A template parameter cannot depend on any local name or class member.
- An unqualified name in a template cannot depend on a local name or class member.
Beginning of C++11 only.
template <class T, class U> int h(T t, U u, decltype(t+u) v);In
this example, the compiler issues an error message if the operand t+u is
invalid after the instantiation of the function template h.For more information, see The decltype(expression) type specifier (C++11)
End of C++11 only.