# Overload Resolution: Candidates, Viability & Ranking

> Trace the three-phase pipeline the compiler runs on every overloaded call—candidate lookup, viability filtering, and conversion-sequence ranking—to predict exact winners and ambiguities.

- **Source:** C++ Atlas (https://cppatlas.com/topics/overload-resolution)
- **Track:** Expressions and functions
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [over.match] (https://eel.is/c++draft/over.match), [over.match.viable] (https://eel.is/c++draft/over.match.viable), [over.match.best] (https://eel.is/c++draft/over.match.best), [over.ics.rank] (https://eel.is/c++draft/over.ics.rank), [over.best.ics] (https://eel.is/c++draft/over.best.ics)
- **cppreference links:** [Overload resolution](https://en.cppreference.com/w/cpp/language/overload_resolution), [Implicit conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion), [Argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl), [Converting constructor](https://en.cppreference.com/w/cpp/language/converting_constructor), [Function template](https://en.cppreference.com/w/cpp/language/function_template)
- **Prerequisites:** name-lookup-and-adl, value-categories, casts-and-qualifiers

When multiple functions share a name, the compiler does not guess by intuition or pick the first match in the file. Instead, `[over.match]` specifies a deterministic three-stage pipeline that takes the call site, narrows down the visible declarations, scores each parameter's conversion path, and declares either one unique winner or a hard ambiguity error.

> **Mental model.** Overload resolution is a tournament with strict rules: first gather all candidates (`lookup + deduction`), eliminate those that cannot accept the call (`viability`), and finally crown the unique candidate that is at least as good on *every* argument and strictly better on *at least one* (`best viable`).

## The three-phase pipeline

Every overloaded function call, constructor call, or operator expression passes through three ordered stages:

1. **Candidate functions.** Name lookup (including ADL for unqualified calls) collects all matching functions. For function templates, template argument deduction (`[temp.deduct]`) runs here: if deduction succeeds, the resulting specialization enters the candidate set; if deduction fails (SFINAE), the specialization is silently dropped before viability even begins.
2. **Viable functions.** A candidate survives Phase 2 only if its parameter count (accounting for default arguments and ellipses) matches the call, any C++20 `requires`-clause evaluates to `true` (`[over.match.viable]/3`), and an implicit conversion sequence exists for every argument.
3. **Best viable function.** All surviving candidates are compared pairwise across every argument (`[over.match.best]`). If no single candidate beats every rival, the call is ill-formed due to ambiguity.

Notice what happens *after* Phase 3 picks the winner: access control (`private`/`protected`) and `= delete` checks! Because deleted functions stay in the viable set, `void f(double) = delete;` intercepts `f(1.5)` and stops compilation rather than silently letting `void f(int)` convert `1.5` to `1`.

## The three-tier conversion hierarchy

To compare how well a viable candidate fits an argument, the compiler assigns an **Implicit Conversion Sequence (ICS)** to each parameter (`[over.best.ics]`) and ranks sequences across three top-level tiers, then three sub-ranks inside Standard Conversions.

| Tier / Sub-rank | Rank | Examples |
| --- | --- | --- |
| **Standard: Exact Match** | Highest | Identity, lvalue-to-rvalue, array-to-pointer, `int*` to `const int*` |
| **Standard: Promotion** | 2nd | `char` or `bool` to `int`, `float` to `double` (value-preserving) |
| **Standard: Conversion** | 3rd | `int` to `double`, `double` to `int`, `Derived*` to `Base*`, `const char*` to `bool` |
| **User-Defined Conversion** | 4th | Single converting constructor or `operator T()` plus standard conversions |
| **Ellipsis Conversion** | Lowest | C-style variadic `...` parameter |

That separation between Standard Conversions and User-Defined Conversions explains one of C++'s sharpest traps.

> **Pitfall.** Given `void log(bool);` and `void log(std::string);`, calling `log("hello")` invokes `log(bool)`! Converting `const char[6]` via array-to-pointer (`const char*`) and pointer-to-boolean (`bool`) is a **Standard Conversion Sequence**, which outranks the **User-Defined Conversion Sequence** calling `std::string(const char*)`.

```cpp
#include <string>

int report(bool flag) { return flag ? 1 : 0; }
int report(const std::string&) { return 2; }

void conversion_trap() {
    // Array-to-pointer + pointer-to-bool is a Standard Conversion;
    // const char* -> std::string is a User-Defined Conversion.
    int a = report("oops");          // Calls report(bool) -> 1!
    int b = report(std::string("ok")); // Calls report(const std::string&) -> 2
    (void)a;
    (void)b;
}
```

## Reference binding, const, and value-category tie-breakers

Inside the **Exact Match** tier, reference parameters follow specialized sub-rules (`[over.ics.rank]/3`) so value categories and `const`-ness dispatch cleanly without extra conversions:

- A **non-`const` lvalue** binds better to `T&` than to `const T&` (and cannot bind to `T&&`).
- A **`const` lvalue** binds only to `const T&`.
- An **rvalue** (prvalue or xvalue) binds better to `T&&` than to `const T&` (and cannot bind to non-`const` `T&`).

Be careful combining by-value overloads (`void f(T)`) with reference overloads (`void f(const T&)` or `void f(T&&)`). Passing `42` to `f(int)` vs `f(const int&)` is **ambiguous** because both parameter forms achieve Exact Match with no meaningful distinction in conversion rank (`[over.ics.rank]/3`).

## Tie-breakers: templates, specializations, and constraints

Suppose two viable candidates tie across every parameter's conversion sequence. Only then does `[over.match.best]/2` consult structural tie-breakers in strict sequence:

1. **Non-template beats template.** Between `void f(int)` and `template <class T> void f(T)`, `f(42)` selects the non-template `f(int)`.
2. **More constrained C++20 concept beats less constrained.** When two templates share identical conversion ranks, constraint **subsumption** (`[temp.constr.order]`) picks the tighter concept (for example, `std::signed_integral<T>` subsumes `std::integral<T>`).
3. **More specialized template wins.** Partial ordering (`[temp.func.order]`) prefers `template <class T> void f(T*)` over `template <class T> void f(T)` for pointers.

> **Standardese.** "Given these definitions, a viable function `F1` is defined to be a better function than another viable function `F2` if for all arguments `i`, `ICSi(F1)` is not a worse conversion sequence than `ICSi(F2)`, and then ... for some argument `j`, `ICSj(F1)` is a better conversion sequence than `ICSj(F2)`, or, if not that, ... `F1` is not a function template specialization and `F2` is a function template specialization..." — `[over.match.best]`

Read that ordering carefully! **Conversion rank ALWAYS precedes the non-template tie-breaker.** If you overload `int pick(const int&)` alongside `template <class T> int pick(T&)`, calling `pick(x)` with a mutable `int x` picks the **template** `pick<int>(int&)`—because binding `int&` to a non-`const` lvalue is a strictly better conversion sequence than binding `const int&`!

```cpp
#include <concepts>

int pick(const int&) { return 1; }
template <class T>
int pick(T&) { return 2; }

int tie(int) { return 1; }
template <class T>
int tie(T) { return 2; }

template <class T>
int check(T) requires std::integral<T> { return 1; }
template <class T>
int check(T) requires std::signed_integral<T> { return 2; }

void ranking_demo() {
    int x = 10;
    int r1 = pick(x);   // Calls template pick<int>(int&) -> 2 (better ref conversion)
    int r2 = tie(x);    // Calls non-template tie(int) -> 1 (conversion ranks tie)
    int r3 = check(x);  // Calls signed_integral overload -> 2 (subsumption)
    (void)r1;
    (void)r2;
    (void)r3;
}
```

One other specialized rule governs braced initialization (`[over.match.list]`): list-initializing a class like `std::vector<int>{5, 1}` runs a two-pass overload resolution that strongly prefers `std::initializer_list` constructors first, explaining why `std::vector<int>{5, 1}` holds two integers (`5` and `1`) while `std::vector<int>(5, 1)` holds five `1`s.

## Member functions, cv/ref-qualifiers, and C++20 operators

For non-static member functions (without C++23 explicit object parameters), the compiler treats `*this` as an extra implicit object parameter during overload resolution (`[over.match.funcs]/4`). Marking a member function `const`, `&`, or `&&` lets `*this` compete cleanly on value category and `const`-qualification—for instance, moving out of a buffer only when invoked on an rvalue (`buf.take() &&`).

Finally, C++20 streamlined comparison overloads (`[over.match.oper]`): defining a single `operator==` lets overload resolution synthesize reversed (`b == a`) and negated (`a != b`, `b != a`) candidates automatically, placing rewritten candidates just below direct non-rewritten matches in tie-breaking.

## What to remember

- **Three steps govern every call.** Gather candidates (lookup + deduction), filter viable signatures (arity + constraints + ICS), then pick the best overall conversion vector.
- **Standard Conversions always beat User-Defined Conversions.** Watch out for pointer-to-`bool` beating `const char*`-to-`std::string`.
- **Conversion rank beats non-template tie-breaking.** A template taking `T&` defeats a non-template taking `const int&` on mutable lvalues.
- **Ambiguity requires no winner, not equal winners.** Being better on parameter 1 and worse on parameter 2 makes a call ill-formed.
- **`= delete` and access checks happen last.** Deleted overloads actively catch bad conversions instead of falling back silently.

## Concept Map Outline

- **Overload Resolution:** Every overloaded call passes through candidate lookup, viability filtering, and conversion ranking.
  - **Three-Phase Pipeline:** Overload resolution constructs candidates, eliminates non-viable matches, and crowns one winner.
    - **1. Build candidate set:** Name lookup, ADL, and template argument deduction gather all visible overloads.
    - **2. Filter viable functions:** Requires matching arity, satisfied C++20 constraints, and an implicit conversion per argument.
    - **3. Pick best viable:** Selects the candidate no worse on every parameter and strictly better on at least one.
  - **Conversion Sequence Tiers:** Implicit conversion sequences rank across three strict tiers before tie-breakers apply.
    - **Standard conversion sequence:** Built-in language conversions outrank all user-defined constructors and operators.
    - **User-defined conversion sequence:** Uses at most one converting constructor or conversion operator between standard conversions.
    - **Ellipsis conversion sequence:** Matches C-style variadic parameters only when no better conversion exists.
  - **Standard Sub-Ranks:** Within standard conversions, exact matches beat promotions, which beat conversions.
    - **Exact match and qualification:** Includes identity, array-to-pointer decay, lvalue-to-rvalue, and adding const qualifiers.
    - **Promotions preserve value:** Widening char, short, or bool to int and float to double beats general conversions.
    - **Lossy and pointer conversions:** Includes int-to-double, Derived*-to-Base*, and pointer-to-bool conversions.
  - **Reference and Qualifier Rules:** Value category and const qualifiers break exact-match ties on references and *this.
    - **Lvalue prefers T& over const:** A mutable lvalue selects T& over const T& because it requires fewer cv-qualifications.
    - **Rvalue prefers T&& over const:** Temporaries and xvalues prefer rvalue references T&& over const T&.
    - **Implicit *this ref-qualifiers:** Member cv and & or && qualifiers participate as the implicit object parameter.
  - **Tie-Breakers and Traps:** When conversions tie completely, language-level rules settle templates, concepts, and deleted calls.
    - **Non-template wins equal ties:** Non-template overloads win only after parameter conversion ranks tie completely.
    - **C++20 constraint subsumption:** More constrained templates beat less constrained templates when conversions tie.
    - **Deleted and private checked last:** Overload resolution selects = delete or private winners before rejecting the call.

## Standardese Quiz Questions

### Question 1 [warmup] ([over.match.best])

Given `void f(int, double);` and `void f(double, int);`, what happens at the call site `f(1, 2);`?

```cpp
void f(int, double);
void f(double, int);

f(1, 2);
```

A. Calls `f(int, double)` because the first parameter is an exact match.
B. Ill-formed due to ambiguity because each candidate is strictly better on one argument and worse on the other.
C. Calls `f(double, int)` because the second parameter converts last.
D. Calls whichever overload was declared earlier in the translation unit.

**Answer (B):** Ill-formed due to ambiguity because each candidate is strictly better on one argument and worse on the other.

**Why:** Under `[over.match.best]`, a winner must be at least as good on *all* arguments and strictly better on at least one. On `f(1, 2)`, the first overload wins argument 1 (`int` exact vs `int->double`), while the second wins argument 2, resulting in an ambiguity error.

### Question 2 [warmup] ([over.match.viable], [dcl.fct.def.delete])

Given `void g(int);` and `void g(double) = delete;`, what happens when calling `g(2.5)`?

```cpp
void g(int);
void g(double) = delete;

g(2.5);
```

A. Calls `g(int)` by truncating `2.5` to `2` because the deleted overload is skipped during viability.
B. Ambiguous between `g(int)` and `g(double)`.
C. Compile error: `g(double)` wins overload resolution and is then rejected as deleted.
D. Undefined behavior at runtime.

**Answer (C):** Compile error: `g(double)` wins overload resolution and is then rejected as deleted.

**Why:** Deleted functions participate in Phase 1 and Phase 2 of overload resolution just like ordinary functions (`[dcl.fct.def.delete]`). Because `2.5` (`double`) is an exact match for `g(double)`, overload resolution selects `g(double)` and then diagnoses the call to a deleted function.

### Question 3 [tricky] ([over.ics.rank], [conv.bool])

Given `int log(bool);` and `int log(const std::string&);`, which overload does `log("hello")` invoke?

```cpp
#include <string>
int log(bool);
int log(const std::string&);

int r = log("hello");
```

A. `log(bool)`, because array-to-pointer plus pointer-to-boolean is a Standard Conversion Sequence.
B. `log(const std::string&)`, because `"hello"` is text.
C. Ambiguous, because both `bool` and `std::string` require one conversion step.
D. Ill-formed, because string literals cannot convert to `bool`.

**Answer (A):** `log(bool)`, because array-to-pointer plus pointer-to-boolean is a Standard Conversion Sequence.

**Why:** In `[over.ics.rank]/2`, *every* Standard Conversion Sequence strictly outranks *every* User-Defined Conversion Sequence. Turning `const char[6]` into `bool` (array-to-pointer + boolean conversion) is purely a Standard Conversion, defeating `std::string(const char*)`.

### Question 4 [tricky] ([over.match.best], [over.ics.rank])

Given `int pick(const int&);` and `template <class T> int pick(T&);`, what does `int x = 10; pick(x);` return?

```cpp
int pick(const int&) { return 1; }
template <class T> int pick(T&) { return 2; }

int x = 10;
int r = pick(x);
```

A. `1`, because non-template functions always beat function templates.
B. Compile error: ambiguous between `const int&` and `T&`.
C. `1`, because `const int&` is preferred for scalar types.
D. `2`, because `int&` has a strictly better reference-binding conversion than `const int&`, before template tie-breaking runs.

**Answer (D):** `2`, because `int&` has a strictly better reference-binding conversion than `const int&`, before template tie-breaking runs.

**Why:** Overload resolution compares conversion sequences *before* applying the non-template-vs-template tie-breaker (`[over.match.best]/2`). Binding mutable lvalue `x` to `int&` (deduced from `T&`) is strictly better than binding to `const int&` (`[over.ics.rank]/3.2.6`), so the template wins.

### Question 5 [standardese] ([over.best.ics], [over.ics.rank])

Why does declaring both `void h(int);` and `void h(const int&);` make the call `h(5)` ambiguous?

```cpp
void h(int);
void h(const int&);

h(5);
```

A. `const int&` cannot bind to a prvalue literal `5`.
B. Both `int` (identity/Exact Match) and `const int&` (Exact Match binding a materialized temporary) have indistinguishable conversion ranks.
C. By-value `int` always ranks lower than reference parameters.
D. Only `h(const int&)` is viable for literals.

**Answer (B):** Both `int` (identity/Exact Match) and `const int&` (Exact Match binding a materialized temporary) have indistinguishable conversion ranks.

**Why:** Under `[over.best.ics]` and `[over.ics.rank]`, passing a prvalue `5` to `int` is an Identity Exact Match, and binding it to `const int&` is also an Exact Match with no distinguishing sub-rank difference against a non-reference parameter. Neither sequence is better, so the call is ambiguous.

### Question 6 [standardese] ([over.match.oper])

In C++20 and C++23, why does `7 != Key{7}` compile when `Key` only defines `friend bool operator==(const Key&, int);`?

```cpp
struct Key {
    int id;
    friend bool operator==(const Key& a, int b) { return a.id == b; }
};
bool diff = (7 != Key{7});
```

A. The compiler generates an implicit conversion from `int` to `Key` automatically.
B. Friend declarations inject free operators for both argument orders automatically.
C. `[over.match.oper]` synthesizes rewritten `!=` and reversed `operator==` candidates during overload resolution.
D. Because `Key` is an aggregate, `!=` performs memberwise comparison.

**Answer (C):** `[over.match.oper]` synthesizes rewritten `!=` and reversed `operator==` candidates during overload resolution.

**Why:** In C++20 (`[over.match.oper]/3`), an expression `a != b` considers rewritten candidates `!(a == b)` and `!(b == a)` synthesized from viable `operator==` overloads, allowing `7 != Key{7}` to resolve to `!(Key{7} == 7)` without writing boilerplate reverse overloads.
