Dependent names - cppreference.com (original) (raw)

Inside the definition of a template (both class template and function template), the meaning of some constructs may differ from one instantiation to another. In particular, types and expressions may depend on types of type template parameters and values of constant template parameters.

template struct X : B // “B” is dependent on T { typename T::A* pa; // “T::A” is dependent on T // (see below for the meaning of this use of “typename”)   void f(B* pb) { static int i = B::i; // “B::i” is dependent on T pb->j++; // “pb->j” is dependent on T } };

Name lookup and binding are different for dependent names and non-dependent names.

Contents

[edit] Binding rules

Non-dependent names are looked up and bound at the point of template definition. This binding holds even if at the point of template instantiation there is a better match:

#include   void g(double) { std::cout << "g(double)\n"; }   template struct S { void f() const { g(1); // “g” is a non-dependent name, bound now } };   void g(int) { std::cout << "g(int)\n"; }   int main() { g(1); // calls g(int)   S s; s.f(); // calls g(double) }

If the meaning of a non-dependent name changes between the definition context and the point of instantiation of a specialization of the template, the program is ill-formed, no diagnostic required. This is possible in the following situations:

lookup for a name in the template definition found a using-declaration, but the lookup in the corresponding scope in the instantiation does not find any declarations because the using-declaration was a pack expansion and the corresponding pack is empty (since C++17)

Binding of dependent names is postponed until lookup takes place.

[edit] Lookup rules

The lookup of a dependent name used in a template is postponed until the template arguments are known, at which time

(in other words, adding a new function declaration after template definition does not make it visible, except via ADL).

The purpose of this rule is to help guard against violations of the ODR for template instantiations:

// an external library namespace E { template void writeObject(const T& t) { std::cout << "Value = " << t << '\n'; } }   // translation unit 1: // Programmer 1 wants to allow E::writeObject to work with vector namespace P1 { std::ostream& operator<<(std::ostream& os, const std::vector& v) { for (int n : v) os << n << ' '; return os; }   void doSomething() { std::vector v; E::writeObject(v); // Error: will not find P1::operator<< } }   // translation unit 2: // Programmer 2 wants to allow E::writeObject to work with vector namespace P2 { std::ostream& operator<<(std::ostream& os, const std::vector& v) { for (int n : v) os << n << ':'; return os << "[]"; }   void doSomethingElse() { std::vector v; E::writeObject(v); // Error: will not find P2::operator<< } }

In the above example, if non-ADL lookup for operator<< were allowed from the instantiation context, the instantiation of E::writeObject<vector<int>> would have two different definitions: one using P1::operator<< and one using P2::operator<<. Such ODR violation may not be detected by the linker, leading to one or the other being used in both instances.

To make ADL examine a user-defined namespace, either std::vector should be replaced by a user-defined class or its element type should be a user-defined class:

namespace P1 { // if C is a class defined in the P1 namespace std::ostream& operator<<(std::ostream& os, const std::vector& v) { for (C n : v) os << n; return os; }   void doSomething() { std::vector v; E::writeObject(v); // OK: instantiates writeObject(std::vectorP1::C) // which finds P1::operator<< via ADL } }

Note: this rule makes it impractical to overload operators for standard library types:

#include #include #include #include   // Bad idea: operator in global namespace, but its arguments are in std:: std::ostream& operator<<(std::ostream& os, std::pair<int, double> p) { return os << p.first << ',' << p.second; }   int main() { typedef std::pair<int, double> elem_t; std::vector v(10); std::cout << v[0] << '\n'; // OK, ordinary lookup finds ::operator<< std::copy(v.begin(), v.end(), std::ostream_iterator(std::cout, " ")); // Error: both ordinary lookup from the point of definition of // std::ostream_iterator and ADL will only consider the std namespace, // and will find many overloads of std::operator<<, so the lookup will be done. // Overload resolution will then fail to find operator<< for elem_t // in the set found by the lookup. }

Note: limited lookup (but not binding) of dependent names also takes place at template definition time, as needed to distinguish them from non-dependent names and also to determine whether they are members of the current instantiation or members of unknown specialization. The information obtained by this lookup can be used to detect errors, see below.

[edit] Dependent types

The following types are dependent types :

a function type whose parameters include one or more function parameter packs (since C++11)
the result of decltype applied to a type-dependent expression The result of decltype applied to a type-dependent expression is a unique dependent type. Two such results refer to the same type only if their expressions are equivalent. (since C++11)
the pack indexing specifier applied to a type-dependent constant expression The pack indexing specifier applied to a type-dependent constant expression is a unique dependent type. Two such pack indexing specifiers refer to the same type only if their constant expressions are equivalent. Otherwise, two such pack indexing specifiers refer to the same type only if their indices have the same value. (since C++26)

Note: a typedef member of a current instantiation is only dependent when the type it refers to is.

[edit] Type-dependent expressions

The following expressions are type-dependent :

contains the special identifier __func__ (if some enclosing function is a template, a non-template member of a class template, or a generic lambda(since C++14)) (since C++11)
contains an identifier for which name lookup finds one or more declarations of member functions of the current instantiation declared with return type deduction (since C++14)
contains an identifier for which name lookup finds a structured binding declaration whose initializer is type-dependent contains an identifier for which name lookup finds a constant template parameter whose type contains the placeholder auto contains an identifier for which by name lookup finds a variable declared with a type that contains a placeholder type (e.g., auto static data member), where the initializer is type-dependent, (since C++17)
contains an identifier for which name lookup finds a pack (since C++26)

The following expressions are never type-dependent because the types of these expressions cannot be:

[edit] Value-dependent expressions

The following expressions are value-dependent :

It is a concept-id and any of its arguments are dependent. (since C++20)

[edit] Dependent names

[edit] Current instantiation

Within a class template definition (including its member functions and nested classes) some names may be deduced to refer to the current instantiation. This allows certain errors to be detected at the point of definition, rather than instantiation, and removes the requirement on the typename and template disambiguators for dependent names, see below.

Only the following names can refer to the current instantiation:

A template argument is equivalent to a template parameter if

template class A { A* p1; // A is the current instantiation A* p2; // A is the current instantiation ::A* p4; // ::A is the current instantiation A<T*> p3; // A<T*> is not the current instantiation   class B { B* p1; // B is the current instantiation A::B* p2; // A::B is the current instantiation typename A<T*>::B* p3; // A<T*>::B is not the current instantiation }; };   template class A<T*> { A<T*>* p1; // A<T*> is the current instantiation A* p2; // A is not the current instantiation };   template struct B { static const int my_I = I; static const int my_I2 = I + 0; static const int my_I3 = my_I; static const long my_I4 = I; static const int my_I5 = (I);   B* b1; // B is the current instantiation: // my_I has the same type as I, // and it is initialized with only I B* b2; // B is not the current instantiation: // I + 0 is not a single identifier B* b3; // B is the current instantiation: // my_I3 has the same type as I, // and it is initialized with only my_I (which is equivalent to I) B* b4; // B is not the current instantiation: // the type of my_I4 (long) is not the same as the type of I (int) B* b5; // B is not the current instantiation: // (I) is not a single identifier };

Note that a base class can be the current instantiation if a nested class derives from its enclosing class template. Base classes that are dependent types but are not the current instantiation are dependent base classes:

template struct A { typedef int M;   struct B { typedef void M;   struct C; }; };   template struct A::B::C : A { M m; // OK, A::M };

A name is classified as a member of the current instantiation if it is

template class A { static const int i = 5;   int n1[i]; // i refers to a member of the current instantiation int n2[A::i]; // A::i refers to a member of the current instantiation int n3[A::i]; // A::i refers to a member of the current instantiation   int f(); };   template int A::f() { return i; // i refers to a member of the current instantiation }

Members of the current instantiation may be both dependent and non-dependent.

If the lookup of a member of current instantiation gives a different result between the point of instantiation and the point of definition, the lookup is ambiguous. Note however that when a member name is used, it is not automatically converted to a class member access expression, only explicit member access expressions indicate members of current instantiation:

struct A { int m; }; struct B { int m; };   template struct C : A, T { int f() { return this->m; } // finds A::m in the template definition context int g() { return m; } // finds A::m in the template definition context };   template int C::f(); // error: finds both A::m and B::m   template int C::g(); // OK: transformation to class member access syntax // does not occur in the template definition context

[edit] Unknown specializations

Within a template definition, certain names are deduced to belong to an unknown specialization, in particular,

template struct Base {};   template struct Derived : Base { void f() { // Derived refers to current instantiation // there is no “unknown_type” in the current instantiation // but there is a dependent base (Base) // Therefore, “unknown_type” is a member of unknown specialization typename Derived::unknown_type z; } };   template<> struct Base // this specialization provides it { typedef int unknown_type; };

This classification allows the following errors to be detected at the point of template definition (rather than instantiation):

template class A { typedef int type;   void f() { A::type i; // OK: “type” is a member of the current instantiation typename A::other j; // Error:   // “other” is not a member of the current instantiation // and it is not a member of an unknown specialization // because A (which names the current instantiation), // has no dependent bases for “other” to hide in. } };

Members of unknown specialization are always dependent, and are looked up and bound at the point of instantiation as all dependent names (see above)

[edit] The typename disambiguator for dependent names

In a declaration or a definition of a template, including alias template, a name that is not a member of the current instantiation and is dependent on a template parameter is not considered to be a type unless the keyword typename is used or unless it was already established as a type name, e.g. with a typedef declaration or by being used to name a base class.

#include #include   int p = 1;   template void foo(const std::vector &v) { // std::vector::const_iterator is a dependent name, typename std::vector::const_iterator it = v.begin();   // without “typename”, the following is parsed as multiplication // of the type-dependent data member “const_iterator” // and some variable “p”. Since there is a global “p” visible // at this point, this template definition compiles. std::vector::const_iterator* p;   typedef typename std::vector::const_iterator iter_t; iter_t * p2; // “iter_t” is a dependent name, but it is known to be a type name }   template struct S { typedef int value_t; // member of current instantiation   void f() { S::value_t n{}; // S is dependent, but “typename” not needed std::cout << n << '\n'; } };   int main() { std::vector v; foo(v); // template instantiation fails: there is no member variable // called “const_iterator” in the type std::vector S().f(); }

The keyword typename may only be used in this way before qualified names (e.g. T::x), but the names need not be dependent.

Usual qualified name lookup is used for the identifier prefixed by typename. Unlike the case with elaborated type specifier, the lookup rules do not change despite the qualifier:

struct A // A has a nested variable X and a nested type struct X { struct X {}; int X; };   struct B { struct X {}; // B has a nested type struct X };   template void f(T t) { typename T::X x; }   void foo() { A a; B b; f(b); // OK: instantiates f, T::X refers to B::X f(a); // error: cannot instantiate f: // because qualified name lookup for A::X finds the data member }

The keyword typename can be used even outside of templates.

#include   int main() { // Both OK (after resolving CWG 382) typedef typename std::vector::const_iterator iter_t; typename std::vector v; }

In some contexts, only type names can validly appear. In these contexts, a dependent qualified name is assumed to name a type and no typename is required: A qualified name that is used as a declaration specifier in the (top-level) decl-specifier-seq of: a simple declaration or function definition at namespace scope; a class member declaration; a parameter declaration in a class member declaration (including friend function declarations), outside of default arguments; a parameter declaration of a declarator for a function or function template whose name is qualified, outside of default arguments; a parameter declaration of a lambda expression outside of default arguments; a parameter declaration of a requires expression; the type in the declaration of a constant template parameter; A qualified name that appears in type-id, where the smallest enclosing type-id is: the type in a new expression that does not parenthesize its type; the type-id in an alias declaration; a trailing return type, a default argument of a type template parameter, or the type-id of a static_cast, dynamic_cast, const_cast, or reinterpret_cast. (since C++20)

[edit] The template disambiguator for dependent names

Similarly, in a template definition, a dependent name that is not a member of the current instantiation is not considered to be a template name unless the disambiguation keyword template is used or unless it was already established as a template name:

template struct S { template void foo() {} };   template void bar() { S s; s.foo(); // error: < parsed as less than operator s.template foo(); // OK }

The keyword template may only be used in this way after operators :: (scope resolution), -> (member access through pointer), and . (member access), the following are all valid examples:

As is the case with typename, the template prefix is allowed even if the name is not dependent or the use does not appear in the scope of a template.

Even if the name to the left of **::** refers to a namespace, the template disambiguator is allowed:

template struct S {};   ::template S q; // allowed, but unnecessary

Due to the special rules for unqualified name lookup for template names in member access expressions, when a non-dependent template name appears in a member access expression (after -> or after .), the disambiguator is unnecessary if there is a class or alias(since C++11) template with the same name found by ordinary lookup in the context of the expression. However, if the template found by lookup in the context of the expression differs from the one found in the context of the class, the program is ill-formed(until C++11) template<int> struct A { int value; };   template<class T> void f(T t) { t.A<0>::value; // Ordinary lookup of A finds a class template. // A<0>::value names member of class A<0> // t.A < 0; // Error: “<” is treated as the start of template argument list } (until C++23)

[edit] Keywords

template,typename

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
CWG 206 C++98 it was unspecified at what point semantic constraints areapplied when a type used in a non-dependent name isincomplete at the point at which a template is defined but iscomplete at the point at which an instantiation is performed the program is ill-formedand no diagnostic isrequired in this case
CWG 224 C++98 the definition of dependent types was basedon the form of the name rather than lookup definition revamped
CWG 382 C++98 the typename disambiguator was only allowed in template scope also allowed outsideof templates
CWG 468 C++98 the template disambiguator was only allowed in template scope also allowed outsideof templates
CWG 502 C++98 it was unspecified whether nested enumerations are dependent dependent as nested classes
CWG 1047 C++98 typeid expressions were never value-dependent value-dependent if theoperand is type-dependent
CWG 1160 C++98 it was unspecified whether a name refers to the current instantiationwhen a template-id matching a primary template or partialspecialization appears in the definition of a member of the template specified
CWG 1413 C++98 uninitialized static data member, static member function, and addressof member of a class template were not listed as value-dependent listed
CWG 1471 C++98 a nested type of a non-dependent base ofthe current instantiation was dependent it is not dependent
CWG 1850 C++98 the list of cases that meaning may change between thedefinition context and the point of instantiation was incomplete made complete
CWG 1929 C++98 it was not clear whether the template disambiguator canfollow a :: where the name to its left refers to a namespace allowed
CWG 2066 C++98 this was never value-dependent it may bevalue-dependent
CWG 2100 C++98 address of a static data member of classtemplate was not listed as value-dependent listed
CWG 2109 C++98 type-dependent identifier expressions might not be value-dependent they are alwaysvalue-dependent
CWG 2276 C++98 a function type whose exception specificationis value-dependent was not a dependent type it is
CWG 2307 C++98 a parenthesized constant template parameter used as atemplate argument was equivalent to that template parameter not equivalent anymore
CWG 2457 C++11 a function type with function parameterpack was not a dependent type it is
CWG 2785 C++20 requires expressions might be type-dependent they are nevertype-dependent
CWG 2905 C++11 a noexcept expression was only value-dependentif its operand is value-dependent it is value-dependentif its operand involvesa template parameter
CWG 2936 C++98 the names of local classes of templatedfunctions were not part of the current instantiation they are