cpp core · advanced
Argument-Dependent Lookup (ADL / Koenig Lookup)
Argument-Dependent Lookup (ADL), also called Koenig lookup. For an unqualified function call f(args), the compiler forms the overload set from two searches: ordinary unqualified lookup AND the namespaces/classes associated with the argument types. So print(w) finds lib::print when w is a lib::Widget, with no lib:: and no using. ADL is why std::cout << x finds operator<< in std, why the using std::swap; swap(a,b); idiom selects a type's custom swap, why range-based for finds begin()/end(), and why hidden friends (functions defined inside a class) are callable at all. It can also surprise you by hijacking a call, which is why std::move/std::forward are deliberately qualified; parenthesizing the callee - (f)(x) - disables ADL.
Argument-Dependent Lookup (ADL / Koenig): an unqualified call f(x) also searches the namespaces and classes associated with x's type - why std::cout << s, the swap idiom, and hidden-friend operators resolve without qualification.
The code
#include <iostream>#include <string>
namespace lib { struct Widget { std::string name; };
// A free function in the SAME namespace as Widget. void print(const Widget& w) { std::cout << "lib::print " << w.name << "\n"; }}
int main() { lib::Widget w{"gizmo"}; print(w); // no 'lib::', no 'using' - yet this compiles // ADL adds w's namespace (lib) to the overload set}What this lesson walks through
- 01The puzzle - no qualifier, yet it compiles
- 02An unqualified call does TWO searches
- 03Ordinary lookup, alone, would fail
- 04ADL adds the argument's namespace
- 05ADL is everywhere in real C++
- 06Pitfalls - and how to switch ADL off
print(w) has no lib:: qualifier and there is no using namespace lib; anywhere. Ordinary name lookup from main could never reach lib::print. Yet the program compiles and prints 'lib::print gizmo'. The rule that rescues it is Argument-Dependent Lookup (ADL), a.k.a. Koenig lookup.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Argument-Dependent Lookup (ADL / Koenig Lookup) and 100+ animated C++ interview lessons.