# Dependent names and two-phase lookup

> A template is checked twice, once when it is defined and once for each set of arguments. Names that do not depend on the template parameters are bound at the definition, dependent names wait for instantiation, and the parser needs `typename` and `template` to read dependent code before it knows what the names mean.

- **Source:** C++ Atlas (https://cppatlas.com/topics/dependent-names-and-two-phase-lookup)
- **Track:** Templates
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [temp.res] (https://eel.is/c++draft/temp.res), [temp.res.general] (https://eel.is/c++draft/temp.res.general), [temp.dep] (https://eel.is/c++draft/temp.dep), [temp.dep.type] (https://eel.is/c++draft/temp.dep.type), [temp.dep.expr] (https://eel.is/c++draft/temp.dep.expr), [temp.dep.res] (https://eel.is/c++draft/temp.dep.res), [temp.dep.candidate] (https://eel.is/c++draft/temp.dep.candidate), [basic.lookup.argdep] (https://eel.is/c++draft/basic.lookup.argdep)
- **cppreference links:** [Dependent names](https://en.cppreference.com/w/cpp/language/dependent_name), [Argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl), [Injected-class-name](https://en.cppreference.com/w/cpp/language/injected-class-name)
- **Prerequisites:** name-lookup-and-adl, template-instantiation-and-specialization

## The one idea

The compiler reads a template definition before it knows the template arguments. Anything in it that does not depend on the template parameters can be checked and resolved immediately, and is. Anything that does depend on them, such as `t.size()` for a parameter `t` of type `T`, can only be resolved when the template is instantiated for a specific `T`. This is **two-phase lookup**: phase one happens at the definition, phase two at each point of instantiation.

Three practical consequences follow. A non-dependent name is bound to whatever is visible at the definition, and later declarations cannot change it. A dependent function call can still find functions declared after the template, but only through argument-dependent lookup. And because the parser must build a syntax tree in phase one, it needs to be told when a dependent name is a type or a template.

> **Mental model.** Phase one asks "what does this mean for every `T`?" and resolves what it can. Phase two fills in the holes for one particular `T`, using argument-dependent lookup as the only window onto declarations that came later.

## What depends on a template parameter

[temp.dep] defines dependency structurally. A **dependent type** is a template parameter, or a type built from one: `T*`, `const T&`, `std::vector<T>`, `T::value_type`, `decltype(t)` where `t` has a dependent type, and so on. An expression is **type-dependent** if its type depends on a template parameter, as `t` and `t + 1` do, and **value-dependent** if its value does, as `sizeof(T)` and a non-type parameter `N` do.

A function call with an unqualified name, such as `f(t)`, is a **dependent call** when any argument is type-dependent. Then the name `f` itself is dependent and is resolved in phase two. A call with no dependent arguments, like `f(1)`, is not dependent, even inside a template.

```cpp
#include <cstdio>

void g(double) { std::puts("g(double)"); }

template<class T> void call(T) { g(1); }  // not dependent: bound to g(double) here

void g(int) { std::puts("g(int)"); }      // too late for call<T>

int main() { call(0); }                    // prints g(double)
```

## Phase one: checked at the definition

In phase one, compilers check syntax, look up every non-dependent name, and diagnose errors in constructs that do not depend on any parameter. GCC and Clang both reject an unqualified call to an undeclared function with no dependent arguments, even in a template that is never instantiated.

```cpp
template<class T> void s() {
  // undeclared();  // error: no arguments depend on T, so a declaration must be visible
}
```

The standard is more permissive about other errors. If no valid specialization of a template could ever be generated, or if a construct that does not depend on a parameter would be ill-formed in a hypothetical instantiation right after the definition, the program is ill-formed with no diagnostic required. Compilers differ in how far they go: Clang 21 rejects `int i = "text";` inside an uninstantiated function template, while GCC 16 says nothing until it instantiates.

> **Standardese.** [temp.res.general] says a program is ill-formed, no diagnostic required, if no valid specialization can be generated for a template, or if a hypothetical instantiation immediately after the definition would be ill-formed because of a construct that does not depend on a template parameter. That is the licence for early diagnosis, not an obligation.

## Phase two: dependent calls and ADL

For a dependent unqualified call, [temp.dep.candidate] combines two lookups. Ordinary unqualified lookup is done only from the template definition context. Argument-dependent lookup is done from both the definition context and the instantiation context. So functions declared after the template are found only if they live in a namespace associated with an argument's type.

```cpp
template<class T> int twice(T t) { return helper(t) * 2; }

namespace lib {
  struct X {};
  int helper(X) { return 21; }   // found by ADL at the point of instantiation
}
int helper(int) { return 1; }    // declared after twice, in the global namespace

int a = twice(lib::X{});         // 42
// int b = twice(0);             // error: int has no associated namespaces,
//                               // and ordinary lookup only saw the definition context
```

That asymmetry is why customization points are found by argument-dependent lookup. A generic algorithm can call `swap(a, b)` unqualified after `using std::swap;`, and the user's `swap` in the user's namespace is found at instantiation even though the algorithm's header was included first. It also explains why such customization does not work for fundamental types: `int` has no associated namespaces, so nothing declared later can be found for it. The general rules of argument-dependent lookup are in the topic on name lookup and ADL.

## `typename` and `template`: telling the parser

In phase one, the compiler does not know whether `T::value_type` names a type, a static data member, or a member template. It assumes a qualified dependent name is not a type unless you say `typename`, and not a template unless you say `template`. The assumption is enforced: without the keyword, the code is parsed as an expression.

```cpp
template<class T> void q() {
  // T::type * ptr;          // parsed as T::type multiplied by ptr, so ptr must exist
  typename T::type* ptr2 = nullptr;  // declares a pointer
  (void)ptr2;
}

template<class T> struct H { template<int N> int get() const { return N; } };

template<class T> int use(const H<T>& h) {
  // return h.get<3>();      // error: parsed as (h.get < 3) > ()
  return h.template get<3>();  // OK: get is a member template
}
```

The same applies to `T::template rebind<U>` and `p->template f<int>()`. The `template` keyword is needed only after `.`, `->` or `::` when the left-hand side is dependent and the name is followed by `<`.

C++20 adopted P0634, which drops the `typename` requirement in contexts where only a type can appear. These include alias declarations, the types of class members and member function returns and parameters, return types and trailing return types of function declarations at namespace scope, the target type of a named cast, and the type in a `new` expression. Inside a function body, where a statement could equally be an expression, `typename` is still required.

```cpp
#include <vector>

template<class T> struct S {
  using V = T::value_type;            // OK since C++20
  T::value_type member;               // OK since C++20
  T::value_type get() const { return member; }  // OK since C++20
  void f() {
    typename T::value_type local{};   // still required in a block
    (void)local;
  }
};
template<class T> T::value_type first(const T& c) { return c[0]; }  // OK since C++20
```

> **Pitfall.** A parameter of a namespace-scope function declaration is not a type-only context unless the declarator is qualified. `template<class T> void p(T::type);` is read as a variable `p` of type `void`, initialized with `T::type`, and rejected. Write `typename` there.

Since C++20, P0846 also lets an unqualified name followed by `<` be treated as a template name when ordinary lookup finds nothing or finds only functions, so `get<0>(t)` finds `std::get` through argument-dependent lookup without a `using` declaration.

## Dependent bases and the current instantiation

Inside a class template, some names are known in phase one even though they are technically dependent. The **current instantiation** is the class being defined: inside `template<class T> struct Node`, the names `Node`, `Node<T>` and `this` all refer to it. Members of the current instantiation are looked up at definition time, so `Node<T>::value_type` needs no `typename` if `value_type` is declared in `Node`, and `this->nope` for a member that does not exist can be diagnosed immediately when the class has no dependent bases.

A base class that depends on a parameter, such as `Base<T>`, is different. It is an **unknown specialization**: someone could explicitly specialize `Base<int>` with completely different members. So unqualified lookup in phase one does not look into dependent bases at all, and an unqualified name used in a derived class template is not found there.

```cpp
template<class T> struct Base { int size() const { return 1; } };

int size() { return 0; }  // an unrelated global function

template<class T> struct Derived : Base<T> {
  int a() const { return this->size(); }    // 1: dependent, found in Base<T> later
  int b() const { return size(); }          // 0: non-dependent, binds to ::size now
  int c() const { return Base<T>::size(); } // 1: qualified (would also suppress virtual dispatch)
};
```

Writing `this->`, qualifying with `Base<T>::`, or adding `using Base<T>::size;` all make the name dependent so it is looked up in phase two. Without a global `size`, `b()` would be a phase-one error: GCC says there are no arguments to `size` that depend on a template parameter. With one, it silently calls the wrong function, which is the nastiest form of this bug. The two disambiguation problems also combine: calling a member template of a dependent base needs both fixes at once, as in `this->template get<0>()`, because `this->get<0>()` would again parse the `<` as less-than. GCC's `-fpermissive` flag turns some of these phase-one errors into warnings, which helps when porting old code but only hides the problem.

> **Pitfall.** Code written for older MSVC versions often relied on finding names in dependent bases without `this->`, because that compiler did not implement two-phase lookup until its `/permissive-` mode. Such code fails on GCC and Clang, or, as above, quietly calls something else.

## What to remember

- Non-dependent names are looked up and bound at the template definition; later declarations do not affect them.
- A call is dependent when an argument is type-dependent; then ordinary lookup uses the definition context and ADL adds the instantiation context.
- Functions declared after a template are found only by ADL, so they are never found for fundamental types.
- A qualified dependent name is assumed to be a value unless marked `typename`, and not a template unless marked `template`.
- C++20 makes `typename` optional where only a type can appear, but not in function bodies or unqualified namespace-scope function parameters.
- Dependent base classes are not searched by unqualified lookup; use `this->`, `Base<T>::` or a using-declaration.
- A template that can never be validly instantiated is ill-formed, no diagnostic required; how early compilers complain varies.

## Concept Map Outline

- **Two-phase lookup:** Non-dependent names resolve at the definition; dependent names resolve at instantiation.
  - **What is dependent:** Dependency is defined structurally from the template parameters.
    - **Dependent types:** T, T*, vector<T>, T::type and decltype of a type-dependent expression.
    - **Dependent expressions:** Type-dependent like t + 1, or value-dependent like sizeof(T) or N.
    - **Dependent calls:** An unqualified call is dependent when any argument is type-dependent.
  - **Phase one:** Checked when the template definition is parsed.
    - **Bound at definition:** Non-dependent names bind to what is visible there; later overloads are ignored.
    - **Early errors:** An undeclared non-dependent function call is rejected even if never instantiated.
    - **Never valid: IFNDR:** No valid specialization possible: ill-formed NDR; Clang diagnoses more than GCC.
  - **Phase two:** Dependent names are resolved for each specialization.
    - **Ordinary lookup:** For dependent calls, only from the template definition context.
    - **ADL both contexts:** Argument-dependent lookup also searches from the point of instantiation.
    - **Fundamental types:** int has no associated namespaces, so later declarations are never found.
  - **Disambiguators:** Tell the parser what a dependent qualified name is.
    - **typename:** Without it, T::type is assumed to be a value; T::type * p is multiplication.
    - **template keyword:** Needed in h.template get<3>() when h is dependent and < follows.
    - **C++20 P0634:** typename optional in type-only contexts such as aliases, members and returns.
    - **Still required:** In function bodies and unqualified namespace-scope function parameters.
  - **Class templates:** Which members are known while the class is being defined.
    - **Current instantiation:** Node, Node<T> and this name it; its members are looked up in phase one.
    - **Dependent bases:** Unknown specializations; unqualified lookup never searches them.
    - **this-> fix:** this->, Base<T>:: or a using-declaration defers the name to phase two.
    - **Silent global:** An unqualified call may bind to a global function instead of the base member.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.dep], [temp.res])

Is this program well-formed?

```cpp
template<class T> struct Base { void hello() {} };

template<class T> struct Derived : Base<T> {
  void run() { hello(); }
};

int main() { Derived<int>{}.run(); }
```

A. Well-formed: `hello` is found in `Base<int>` when `Derived<int>` is instantiated
B. Ill-formed: `hello` is not found, because unqualified lookup does not search the dependent base `Base<T>`
C. Ill-formed, no diagnostic required
D. Well-formed only because `Base<int>` is not explicitly specialized

**Answer (B):** Ill-formed: `hello` is not found, because unqualified lookup does not search the dependent base `Base<T>`

**Why:** `hello()` has no arguments, so it is not a dependent call and is looked up in phase one. Unqualified lookup at the definition does not look into `Base<T>`, a dependent base, because a specialization of `Base` could have entirely different members. Nothing named `hello` is visible, so the program is ill-formed and GCC and Clang both reject it. Writing `this->hello()` or `Base<T>::hello()` makes the name dependent and fixes it.

### Question 2 [warmup] ([temp.names], [temp.res])

`use` fails to compile because `h.get<3>()` is parsed as comparisons. What is the correct spelling of the return expression?

```cpp
template<class T> struct H { template<int N> int get() const { return N; } };

template<class T> int use(const H<T>& h) {
  return h.get<3>();
}

int x = use(H<int>{});
```

A. `return typename h.get<3>();`
B. `return h.template get<3>();`
C. `return h.get template<3>();`
D. No change: since C++20 the compiler looks inside `H<T>` to see that `get` is a template

**Answer (B):** `return h.template get<3>();`

**Why:** `h` has a dependent type, so in phase one the compiler cannot know that `get` is a member template, and without help the `<` is a less-than operator; the original code is ill-formed. The `template` keyword after `.` tells the parser that the next name is a template. `typename` marks types, not templates, and C++20 relaxed only `typename` in type-only contexts and the lookup of unqualified template-ids, neither of which helps a member access.

### Question 3 [warmup] ([temp.res], [temp.dep])

What does this program print?

```cpp
#include <cstdio>

void g(double) { std::puts("g(double)"); }

template<class T> void call(T) { g(1); }

void g(int) { std::puts("g(int)"); }

int main() { call(0); }
```

A. `g(int)`
B. Ill-formed: the call `g(1)` is ambiguous
C. `g(double)`
D. It depends on the compiler

**Answer (C):** `g(double)`

**Why:** `g(1)` has no type-dependent arguments, so it is not a dependent call: it is looked up and bound at the template definition, where only `g(double)` is visible. The later `g(int)` would be a better match, which is why `g(int)` is tempting, but it is never considered for this call. If the call were `g(T{})`, it would be dependent, though ordinary lookup would still see only `g(double)`, and argument-dependent lookup finds nothing for `int`.

### Question 4 [tricky] ([temp.dep], [temp.res])

What does this program return?

```cpp
template<class T> struct Base { int size() const { return 1; } };

int size() { return 0; }

template<class T> struct Derived : Base<T> {
  int n() const { return size(); }
};

int main() { return Derived<int>{}.n(); }
```

A. 0
B. 1
C. Ill-formed: the call is ambiguous between `::size` and `Base<int>::size`
D. Ill-formed: `size` is not found in `Base<T>`

**Answer (A):** 0

**Why:** `size()` is not a dependent call, so it is looked up at the definition, and unqualified lookup skips the dependent base `Base<T>`. It finds the global `::size`, binds to it, and `n` returns 0. There is no ambiguity, because `Base<int>::size` is never a candidate. Without the global function, the program would be ill-formed as the last option says; with it, the bug is silent.

### Question 5 [tricky] ([temp.dep.candidate], [basic.lookup.argdep])

Which of the two uses of `twice` are well-formed?

```cpp
template<class T> int twice(T t) { return helper(t) * 2; }

namespace lib {
  struct X {};
  int helper(X) { return 21; }
}
int helper(int) { return 1; }

int a = twice(lib::X{});  // #1
int b = twice(0);         // #2
```

A. Both: `helper` is looked up at the point of instantiation, where both overloads are visible
B. Only #2
C. Neither: `helper` must be declared before the template
D. Only #1

**Answer (D):** Only #1

**Why:** `helper(t)` is a dependent call. Ordinary unqualified lookup is done only from the definition context, where no `helper` exists, and argument-dependent lookup is done from both the definition and instantiation contexts. For `lib::X`, ADL searches `lib` and finds `lib::helper`. For `int`, there are no associated namespaces, so the global `helper(int)` declared after the template is never found and #2 is ill-formed. The first option describes a single lookup at instantiation, which is not the rule.

### Question 6 [tricky] ([temp.res], [temp.res.general])

How does a conforming compiler parse the statement in `q`?

```cpp
template<class T> void q() {
  T::type * ptr;
}
```

A. As a declaration of `ptr`, a pointer to `T::type`
B. As a multiplication of `T::type` by `ptr`, which here is ill-formed because `ptr` is not declared
C. It is deferred until instantiation, when the compiler knows what `T::type` is
D. As a declaration in C++20 and later, because P0634 made `typename` optional

**Answer (B):** As a multiplication of `T::type` by `ptr`, which here is ill-formed because `ptr` is not declared

**Why:** A qualified name that depends on a template parameter is assumed not to name a type unless it is preceded by `typename`, so the statement is an expression: `T::type` times `ptr`. `ptr` is a non-dependent name and is undeclared, so phase one rejects the template. P0634 removed the need for `typename` only in contexts where a type is the only possible parse, and a statement in a function body is not one of them.

### Question 7 [standardese] ([temp.res.general])

In C++23, in which of these positions inside `template<class T> struct S { ... };` is `typename` still required before `T::value_type`?

A. `using V = T::value_type;`
B. `T::value_type member;` as a data member
C. `void set(T::value_type v);` as a member function parameter
D. `void f() { T::value_type local{}; }` inside a member function body
E. `auto g() -> T::value_type;` as a trailing return type

**Answer (D):** `void f() { T::value_type local{}; }` inside a member function body

**Why:** C++20's P0634 defines type-only contexts in which a dependent qualified name is assumed to be a type: alias declarations, the decl-specifiers of member declarations, parameters in member declarations, trailing return types, named cast targets and a few more. A statement in a function body is not such a context, because `T::value_type local{};` could equally be an expression, so `typename` is still required there. All the other positions compile without it in C++20 and later.

### Question 8 [standardese] ([temp.res.general])

The function template `u` is never instantiated. What does the C++23 standard say about this translation unit?

```cpp
template<class T> void u() {
  int i = "text";
  (void)i;
}

int main() {}
```

A. Well-formed: templates are only checked when instantiated
B. Ill-formed, and a diagnostic is required
C. Undefined behavior
D. Ill-formed, no diagnostic required

**Answer (D):** Ill-formed, no diagnostic required

**Why:** The initialization does not depend on `T`, and it would be ill-formed in a hypothetical instantiation right after the definition; no valid specialization of `u` can be generated either. [temp.res.general] makes such a program ill-formed with no diagnostic required. That permits early diagnosis without requiring it: Clang 21 rejects this translation unit, while GCC 16 accepts it, which is why the first option looks right on GCC.
