skip to content

In C++, what is argument-dependent lookup, and why does std::cout << v need it to find an operator<< declared in v's namespace?

level: middleimportance: must knowfreq 62%

answer

  1. unqualified calls only
  2. the arguments' namespaces join the search
  3. operators cannot be qualified comfortably
  4. parentheses switch it off

basics

~20 s

Argument-dependent lookup adds, for an unqualified function call, the functions declared in the namespaces of the argument types. It lets std::cout << v find geo::operator<< for a geo::Vec2 without a qualifier or a using-declaration at every call site.

solid answer

~50 s

**Argument-dependent lookup** (ADL, also called Koenig lookup) applies when a function call names the function with an **unqualified** name. Besides ordinary lookup, the compiler searches the **associated namespaces** of the argument types: for a class, the namespace it is declared in, plus those of its bases and, for a template specialization, of its template arguments. Operators are the reason it exists. `std::cout << v` is a call to `operator<<(std::cout, v)`, and the operator for `geo::Vec2` lives in `geo`; without ADL every caller would need a using-declaration or the unreadable `geo::operator<<(std::cout, v)`. ADL is skipped when ordinary lookup finds a class member, a block-scope function declaration or something that is not a function, and writing `(f)(x)` switches it off. Its cost is surprise: a function from an argument's namespace can join or hijack a call you meant for your own helper.

code

cpp · 18 lines
cpp
#include <iostream>

namespace geo {
struct Vec2 { double x, y; };

std::ostream& operator<<(std::ostream& os, const Vec2& v) {
    return os << '(' << v.x << ", " << v.y << ')';
}

double dot(const Vec2& a, const Vec2& b) { return a.x * b.x + a.y * b.y; }
}  // namespace geo

int main() {
    geo::Vec2 a{1, 2}, b{3, 4};
    std::cout << a << '\n';         // operator<< found in geo by ADL
    std::cout << dot(a, b) << '\n'; // unqualified dot: ADL looks in geo
    // std::cout << (dot)(a, b);    // error: parentheses switch ADL off
}

go deeper

for a junior

Know that std::cout << value finds an operator<< declared next to the value's type because the arguments decide where the compiler looks.

for a middle

State the rule exactly: unqualified call, associated namespaces of the argument types including template arguments, and the cases that switch ADL off, such as a member found by ordinary lookup or a parenthesized name.

for a senior

Show you have met the hazard: an ambiguous or hijacked call through std types, fixed by qualifying, renaming or moving helpers into their own namespace.

for a principal

Argue for the convention that a type's operators and customization functions live in its namespace, and that cross-namespace utility calls are qualified, so ADL stays an asset rather than a source of surprise.

## The problem ADL solves Put a type and its operations in a namespace, as any library does: ```cpp namespace geo { struct Vec2 { double x, y; }; std::ostream& operator<<(std::ostream& os, const Vec2& v); double dot(const Vec2& a, const Vec2& b); } ``` Now write `std::cout << a` in `main`. The expression is a call to an `operator<<` with arguments `std::cout` and `a`. Ordinary unqualified lookup from `main` searches the block, then the global namespace, and never looks inside `geo`. Without help, the only spellings that work would be `geo::operator<<(std::cout, a)` or a `using geo::operator<<;` at every call site. Infix operators would be unusable for types in namespaces, which means for every serious library. **Argument-dependent lookup** fixes that by letting the arguments say where to look. ## The rule When the function in a call expression is named by an **unqualified-id**, the set of candidates is the union of: - what **ordinary unqualified lookup** finds from the call site, and - what a search of the arguments' **associated namespaces** finds. ADL does not run, and only ordinary lookup counts, when ordinary lookup finds any of: 1. a **class member**, as in a member function calling another member; 2. a **function declared at block scope** (not a using-declaration); 3. a declaration that is **not a function or function template**, such as a variable or a type. A qualified name such as `geo::dot(a, b)` never uses ADL, and neither does a parenthesized name: the standard's own example shows `(f)(s)` failing where `f(s)` finds `N::f`. ## What counts as an associated namespace | Argument type | Where ADL looks | |---|---| | `geo::Vec2` (a class) | `geo`, plus the namespaces of `Vec2`'s base classes | | `std::vector<geo::Vec2>` (a class template specialization) | `std` and also `geo`, from the template argument | | `geo::Color` (an enumeration) | `geo` | | `geo::Vec2*` or an array of `geo::Vec2` | as for `geo::Vec2` | | `int`, `double`, `int*` | nowhere: fundamental types add no namespace | ADL also finds **friend functions** defined inside the associated classes, even though ordinary lookup cannot see them; that is the basis of the hidden-friend idiom. Inline namespaces are folded in both ways: if a type lives in `geo::v2` and `v2` is inline, `geo` is searched too. ## The surprise side: hijacked and ambiguous calls Because ADL searches places the caller never named, an unqualified call can pick up functions the author did not intend: ```cpp template <class It> long distance(It first, It last); // a project helper at global scope std::vector<int> v{1, 2, 3}; int raw[3]{}; distance(raw, raw + 3); // int*: no associated namespace, finds ::distance distance(v.begin(), v.end()); // error with libc++: call to 'distance' is ambiguous ``` With libc++ the vector iterator is a class in namespace `std`, so ADL adds `std::distance`, and both templates are equally good matches. Whether this breaks depends on the library implementation: an implementation whose `vector` iterator were a plain pointer would add no namespace. The remedies: - **Qualify** a call when you mean one specific function: `::distance(...)` or `std::distance(...)`. - Give project helpers names unlikely to exist in `std`, or put them in your own namespace and qualify them. - Keep a type's operators and customization functions (`operator<<`, `operator==`, `swap`, `begin`, `end`) **in the type's own namespace**, so ADL finds them wherever the type travels. C++20 turned the third suppression rule into a design tool. Its **customization point objects**, such as `std::ranges::begin` and `std::ranges::swap`, are objects rather than functions. When ordinary lookup finds one of them, it has found a declaration that is not a function, so ADL is switched off for that call and nothing in an argument's namespace can hijack it. The object's call operator then tries a fixed sequence of spellings, which includes an argument-dependent call to the type's own `begin` or `swap` (for `std::ranges::begin`, after a member `begin()`), so the type's customization is still reached. ## Why interviewers ask it ADL explains several things candidates use without noticing: `std::cout << "hi"` finding `std::operator<<` for `const char*` because `std::cout` is an argument, the `using std::swap; swap(a, b);` idiom, and hidden friends. The expected answer has three parts: the rule (unqualified call, arguments' namespaces), the reason (operators and customization points for namespaced types), and the hazard (unintended candidates, ambiguities, and the qualification or naming discipline that avoids them).

  • Why does std::cout << "hello" work without any using-declaration?
    The expression calls operator<< with std::cout as an argument. Its type, std::ostream, is a class in namespace std, so ADL searches std and finds the operator<< overloads for character pointers declared there. Members of basic_ostream also participate, because operator lookup in an expression considers member candidates of the left operand too.
  • When does ordinary lookup prevent ADL from running at all?
    When ordinary unqualified lookup finds a class member, a function declared at block scope (not a using-declaration), or a declaration that is not a function or function template, such as a variable. Then only that result counts. Inside a member function, calling another member's name therefore never consults the arguments' namespaces.

  • ADL applies to qualified calls such as geo::dot(a, b) too
  • ADL searches every namespace in the program for a matching function
  • Passing an int lets ADL look in the namespace of the calling function
  • ADL only matters for operators, never for named functions
  • Template arguments of a class type never add associated namespaces