# Customization points and niebloids

> Generic code needs a way to call "the right swap" or "the right begin" for a type it has never seen. C++ moved from the ADL two-step to customization point objects and niebloids, function objects that do the lookup for you and cannot be hijacked by it, and settled on hidden friends as the way for types to plug in.

- **Source:** C++ Atlas (https://cppatlas.com/topics/customization-points-and-niebloids)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [basic.lookup.argdep] (https://eel.is/c++draft/basic.lookup.argdep), [customization.point.object] (https://eel.is/c++draft/customization.point.object), [concept.swappable] (https://eel.is/c++draft/concept.swappable), [range.access.begin] (https://eel.is/c++draft/range.access.begin), [algorithms.requirements] (https://eel.is/c++draft/algorithms.requirements), [hidden.friends] (https://eel.is/c++draft/hidden.friends), [namespace.std] (https://eel.is/c++draft/namespace.std)
- **cppreference links:** [Customization point object](https://en.cppreference.com/w/cpp/ranges/cpo), [std::ranges::swap](https://en.cppreference.com/w/cpp/utility/ranges/swap), [std::ranges::begin](https://en.cppreference.com/w/cpp/ranges/begin), [Constrained algorithms (algorithm function objects)](https://en.cppreference.com/w/cpp/algorithm/ranges), [Argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl), [Extending the namespace std](https://en.cppreference.com/w/cpp/language/extending_std)
- **Prerequisites:** name-lookup-and-adl, concepts-and-constraints, template-instantiation-and-specialization

## The one idea

A library function such as `sort` has to swap elements of a type it knows nothing about. The type's author may have written a fast `swap`, or may have written nothing, in which case three moves will do. Somebody has to decide which to call, and the decision must happen where the type's author can influence it without editing the library.

For twenty years the answer was argument-dependent lookup, used through an idiom every caller had to remember. C++20 moved the idiom into the library: `std::ranges::swap`, `std::ranges::begin` and their relatives are **customization point objects**, constant function objects whose call operator performs the right lookup, checks the result, and falls back sensibly. The constrained algorithms in `std::ranges` are function objects for a related reason: an object found by ordinary lookup switches ADL off.

> **Mental model.** A customization point object is the two-step idiom written once, correctly, inside the library. You call it with a qualified name; it does the unqualified, ADL-only call on your behalf.

How ADL decides which namespaces to search is covered in the name-lookup-and-adl topic. Here the question is how libraries use it.

## The ADL two-step and how it fails

The classic idiom brings `std::swap` into scope as a fallback and then makes an unqualified call, so ADL can find a better `swap` in the argument's namespace.

```cpp
#include <cstdio>
#include <utility>

namespace lib {
  struct Widget {
    int id;
    friend void swap(Widget& a, Widget& b) noexcept {
      std::puts("lib swap");
      std::swap(a.id, b.id);
    }
  };
}

template <class T> void good(T& a, T& b) { using std::swap; swap(a, b); }
template <class T> void bad(T& a, T& b) { std::swap(a, b); }

int main() {
  lib::Widget a{1}, b{2};
  good(a, b);  // prints lib swap
  bad(a, b);   // prints nothing: generic std::swap, three moves
}
```

Every part of the idiom can go wrong, and every failure compiles.

- **Qualifying the call.** `std::swap(a, b)` suppresses ADL, so the type's own `swap` is silently skipped. The code is correct but may be slow, or may lose an invariant the custom `swap` preserved.
- **Forgetting the using-declaration.** Without `using std::swap;`, the unqualified call finds nothing for `int` or for types without their own `swap`, and generic code breaks only for some instantiations.
- **No constraints.** Nothing checks that the function ADL found actually swaps, or that a `begin` found the same way returns an iterator.
- **Hijacking.** ADL searches every namespace associated with the argument types, including those of template arguments. An unconstrained function template with the right name in any of those namespaces can be a better match than the one you meant, or make the call ambiguous.

## Customization point objects

A customization point object, as [customization.point.object] describes it, is a constant function object of a literal, semiregular type. Its call operator is constrained, so a failed customization is a substitution failure rather than a hard error. Each one tries a fixed sequence of strategies and takes the first that is valid.

`std::ranges::swap(t, u)`, specified in [concept.swappable], tries:

1. An unqualified `swap(t, u)` when either argument has class or enumeration type, with overload resolution performed in a context that also sees a deleted `template<class T> void swap(T&, T&)`. That deleted candidate makes the unconstrained `std::swap` lose to an ambiguity, so only a genuine customization is chosen. If the function found does not exchange the values, the program is ill-formed, no diagnostic required.
2. Otherwise, for two lvalue arrays of equal extent, `ranges::swap_ranges`.
3. Otherwise, for two lvalues of the same move-constructible and move-assignable type, an exchange through moves, with a `noexcept` computed from the type.

`std::ranges::begin(t)` checks an array first, then a member `t.begin()`, then an ADL-only `begin(t)`, and in each case requires the result to model `input_or_output_iterator`. It also refuses an rvalue argument unless the type is a borrowed range, which the borrowed-ranges-and-dangling topic explains. `ranges::size` goes array extent, member `size()`, ADL `size()`, and finally `end - begin` for sized sentinels.

```cpp
#include <ranges>

namespace lib {
  struct Bag { int data[3]{1, 2, 3}; };
  int* begin(Bag& b) { return b.data; }   // found by ADL
  int* end(Bag& b) { return b.data + 3; }

  struct Both {
    int d[2]{};
    int* begin() { return d; }            // member wins
    int* end() { return d + 2; }
  };
  int* begin(Both&) = delete;             // never considered
}

static_assert(std::ranges::range<lib::Bag>);
static_assert(std::ranges::range<lib::Both>);
static_assert(!std::ranges::range<const lib::Bag>);  // no const overloads
```

C++20 originally specified deleted "poison pill" overloads for `begin`, `end`, `size` and their relatives as well. The defect report P2602 replaced those with a plain requirement that the lookup be argument-dependent only, which is how the C++23 wording reads.

> **Standardese.** [customization.point.object] says all instances of a customization point object's type are equal, and the effect of calling one does not depend on whether the object expression is an lvalue or an rvalue, const or not. That is what makes it safe to copy a CPO into an algorithm, or to call it through a reference.

## Why objects, and what niebloids are

Being an object matters for two reasons. The first is that an object can be passed around: `std::ranges::transform(vs, out, std::ranges::size)` works, while taking the address of most standard functions is unspecified since C++20. The second is about lookup. [basic.lookup.argdep] says that if ordinary unqualified lookup finds something that is not a function or function template, such as a variable, ADL is not performed at all. A CPO in scope therefore cannot be supplemented or hijacked by ADL, so `using std::ranges::swap; swap(a, b);` simply calls the object, which then does its own careful lookup internally.

The constrained algorithms, `std::ranges::sort`, `std::ranges::find` and the rest, rely on the same property. Eric Niebler's range-v3 library implemented them as function objects so they behave like this, and they acquired his name: **niebloids**. [algorithms.requirements] in C++20 and C++23 states the effect without demanding an implementation technique: these entities are not found by ADL, and when found by unqualified lookup they inhibit ADL. C++26, through P3136, specifies them directly as algorithm function objects.

```cpp
#include <algorithm>
#include <cstdio>
#include <vector>

namespace lib {
  struct Rec { int v; bool operator==(const Rec&) const = default; };
  template <class It, class T> It find(It, It last, const T&) { return last; }
}

void f(std::vector<lib::Rec>& v) {
  using std::ranges::find;
  auto it = find(v.begin(), v.end(), lib::Rec{1});  // std::ranges::find, ADL off
  (void)it;
  // With 'using std::find;' instead, ADL adds lib::find (lib is associated
  // through vector<lib::Rec>), and the call is ambiguous.
}
```

> **Pitfall.** A niebloid's constraints are stricter than the old algorithm's. `std::ranges::find` requires the element and the value to be comparable with `==` in the sense of `indirect_binary_predicate`, so code that compiled with `std::find` can fail with the `ranges` version until the types are fixed.

## tag_invoke, and why it was left behind

CPOs solved calling, but defining a new CPO meant reserving a new global name for ADL to search, such as `swap`, `begin`, `iter_move`. The tag_invoke proposal, P1895, generalized this: every customization goes through one ADL name, `tag_invoke`, and the CPO object itself is passed as the first argument to say which operation is meant.

```cpp
#include <type_traits>
#include <utility>

namespace my {
  struct tag_invoke_fn {
    template <class Tag, class... Args>
    constexpr auto operator()(Tag t, Args&&... args) const
        -> decltype(tag_invoke(t, std::forward<Args>(args)...)) {
      return tag_invoke(t, std::forward<Args>(args)...);
    }
  };
  inline constexpr tag_invoke_fn tag_invoke_cpo{};

  inline constexpr struct get_name_fn {
    template <class T>
    constexpr auto operator()(const T& t) const -> decltype(tag_invoke_cpo(*this, t)) {
      return tag_invoke_cpo(*this, t);
    }
  } get_name{};
}

struct Dog {
  friend const char* tag_invoke(decltype(my::get_name), const Dog&) { return "dog"; }
};

inline const char* dog_name() { return my::get_name(Dog{}); }  // "dog"
```

It works, and libraries such as libunifex and early drafts of `std::execution` used it widely. It was not adopted into the standard. Every customization of every operation joins one overload set named `tag_invoke`, which hurts compile times and produces error messages that list every candidate in sight. The definitions are hard to read and to search for. When `std::execution` was finalized for C++26 (P2300, revised by P2855), its customizations moved to member functions and environment queries instead. A language feature for customizable functions has been proposed and has not been adopted.

## How to customize today

For your own types, provide the operation as a **hidden friend**: a friend function defined inside the class. It lives in the enclosing namespace but is invisible to ordinary lookup, so only ADL with an argument of your type can find it. [hidden.friends] specifies that the friend functions the standard library itself declares inside its classes are hidden friends in exactly this sense.

```cpp
#include <cstdio>

namespace geo {
  struct Meters {
    double v;
    Meters(double d) : v(d) {}
    friend void print(Meters m) { std::printf("%g m\n", m.v); }
  };
}

int main() {
  geo::Meters m{2.0};
  print(m);         // OK: found by ADL
  // print(3.0);    // error: no argument of type Meters, so no ADL into geo
  // geo::print(m); // error: qualified lookup cannot see a hidden friend
}
```

Hidden friends keep overload sets small, avoid accidental conversions from unrelated types, and make compile errors shorter. Customization point objects find them, which is all most types need: a hidden `swap`, `begin` and `end`, `iter_move` and `iter_swap` for iterators.

Some customization still happens by specializing templates in `std`, and [namespace.std] limits it tightly.

- A **class template** may be specialized if the specialization depends on a program-defined type and meets the original's requirements: `std::hash`, `std::formatter`, `std::tuple_size`, `std::common_type`, `std::basic_common_reference`.
- The type traits in `<type_traits>` may not be specialized, apart from `common_type` and `basic_common_reference`. Specializing `std::is_integral` for your type is undefined behavior.
- A **variable template** may be specialized only where the standard says so, as for `std::ranges::enable_borrowed_range`, `enable_view`, `disable_sized_range` and `std::disable_sized_sentinel_for`.
- **Function templates** may no longer be specialized since C++20 (P0551). `template<> void std::swap(Widget&, Widget&)` was allowed before and is undefined behavior now. Adding overloads to `std` was never allowed.

## What to remember

- The two-step `using std::swap; swap(a, b);` works, but qualifying the call or forgetting the using-declaration silently does the wrong thing.
- Customization point objects perform the two-step for you, constrain the result, and fall back in a fixed order.
- `ranges::begin` tries array, member, then ADL; `ranges::swap` tries ADL `swap`, then arrays, then moves.
- Ordinary lookup finding an object disables ADL, so CPOs and niebloids cannot be hijacked.
- The `std::ranges` algorithms are niebloids: never found by ADL, and they inhibit it when found by unqualified lookup.
- `tag_invoke` funnelled all customization through one name and was dropped; C++26 `std::execution` uses members and queries.
- Customize with hidden friends; only ADL can find them.
- Specialize `std` class templates only for your own types, never type traits, and never function templates since C++20.

## Concept Map Outline

- **Customization points:** How generic code calls the right operation for a type it has never seen.
  - **ADL two-step:** using std::swap; swap(a, b); lets ADL find a better swap, with std::swap as fallback.
    - **Qualified call:** std::swap(a, b) suppresses ADL and silently skips the type's own swap.
    - **Missing using:** Without the using-declaration, ints and types lacking swap fail to compile.
    - **Hijacking:** Any same-named template in an associated namespace can win or cause ambiguity.
  - **CPOs:** Const semiregular function objects that do the lookup, check it, and fall back.
    - **ranges::swap order:** ADL swap with a deleted swap(T&, T&) candidate, then equal-extent arrays, then moves.
    - **ranges::begin order:** Array, then member begin(), then ADL-only begin(); result must be an iterator.
    - **ranges::size order:** Array extent, member size(), ADL size(), then end minus begin for sized sentinels.
    - **P2602 cleanup:** Defect report against C++20 replaced poison pills for begin, end, size with ADL-only wording.
  - **Why objects:** Objects can be passed around and are immune to ADL.
    - **ADL suppression:** If unqualified lookup finds a variable, [basic.lookup.argdep] performs no ADL.
    - **Passable:** ranges::size can be an algorithm argument; most std functions cannot be addressed.
    - **All instances equal:** Calling a CPO does not depend on the object's value category or constness.
  - **Niebloids:** The std::ranges algorithms, named after Eric Niebler's range-v3 technique.
    - **C++20 and C++23:** Not found by ADL, and they inhibit ADL when found by unqualified lookup.
    - **C++26:** P3136 specifies them directly as algorithm function objects.
    - **Stricter constraints:** ranges::find needs indirect_binary_predicate; some std::find calls do not port.
  - **tag_invoke:** P1895: one ADL name for all customizations, with the CPO passed as a tag.
    - **Costs:** One giant overload set: slow compiles, long errors, hard-to-read definitions.
    - **Not adopted:** C++26 std::execution moved to member functions and environment queries.
  - **Customizing today:** Hidden friends for operations; narrow rules for specializing std templates.
    - **Hidden friends:** Defined in the class, found only by ADL; no conversions from unrelated types.
    - **Class templates:** Specialize hash, formatter, tuple_size for program-defined types only.
    - **Type traits:** Specializing <type_traits> templates is UB except common_type and basic_common_reference.
    - **Function templates:** Specializing them is undefined behavior since C++20 (P0551).

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.lookup.argdep], [utility.swap])

What does this program print?

```cpp
#include <cstdio>
#include <utility>

namespace lib {
  struct Widget {
    int id;
    friend void swap(Widget& a, Widget& b) noexcept {
      std::puts("lib swap");
      std::swap(a.id, b.id);
    }
  };
}

template <class T> void exchange_them(T& a, T& b) { std::swap(a, b); }

int main() {
  lib::Widget a{1}, b{2};
  exchange_them(a, b);
}
```

A. `lib swap`
B. Nothing
C. `lib swap` twice
D. It is ill-formed: the call is ambiguous

**Answer (B):** Nothing

**Why:** A qualified call `std::swap(a, b)` performs no argument-dependent lookup, so the hidden friend in `lib` is never a candidate. The generic `std::swap` template exchanges the values with one move construction and two move assignments, printing nothing. To reach the custom `swap`, write `using std::swap; swap(a, b);` or call `std::ranges::swap(a, b)`.

### Question 2 [warmup] ([hidden.friends], [basic.lookup.argdep], [namespace.memdef])

Which statement about the two marked calls is true?

```cpp
#include <cstdio>

namespace geo {
  struct Meters {
    double v;
    Meters(double d) : v(d) {}
    friend void print(Meters m) { std::printf("%g m\n", m.v); }
  };
}

int main() {
  geo::Meters m{2.0};
  print(m);    // 1
  print(3.0);  // 2
}
```

A. Both compile; call 2 converts `3.0` to `Meters`
B. Call 1 is ill-formed because `print` is not declared at namespace scope
C. Call 2 is ill-formed: no argument has type `Meters`, so ADL never looks inside `geo`
D. Both are ill-formed, because a friend function cannot be called without qualification

**Answer (C):** Call 2 is ill-formed: no argument has type `Meters`, so ADL never looks inside `geo`

**Why:** A friend defined only inside a class is a hidden friend: it belongs to `geo` but ordinary lookup cannot find it, and only argument-dependent lookup triggered by an argument of type `Meters` can. Call 1 has such an argument, so it works. Call 2 passes a `double`, which has no associated namespaces, so the name is not found at all and the implicit conversion is never considered. That is a deliberate benefit of hidden friends.

### Question 3 [warmup] ([basic.lookup.argdep], [concept.swappable], [customization.point.object])

What does this program print?

```cpp
#include <concepts>
#include <cstdio>
#include <utility>

namespace lib {
  struct Widget {
    int id;
    friend void swap(Widget& a, Widget& b) noexcept {
      std::puts("lib swap");
      std::swap(a.id, b.id);
    }
  };
}

int main() {
  lib::Widget a{1}, b{2};
  using std::ranges::swap;
  swap(a, b);
}
```

A. `lib swap`
B. Nothing: the using-declaration names an object, so ADL is switched off and `lib::swap` is never called
C. `lib swap` twice
D. It is ill-formed: the call is ambiguous between the object and the friend

**Answer (A):** `lib swap`

**Why:** Ordinary lookup finds the object `std::ranges::swap`, and because it is not a function, ADL is not performed for this call, so there is no ambiguity. The object's call operator then performs its own unqualified, ADL-based lookup for `swap(t, u)`, which finds the hidden friend and prints once. The second option is right that ADL is suppressed at the call site, but misses that the customization point object does the lookup internally.

### Question 4 [tricky] ([basic.lookup.argdep], [over.match.best], [algorithms.requirements])

What happens with the call to `find`?

```cpp
#include <algorithm>
#include <vector>

namespace lib {
  struct Rec { int v; bool operator==(const Rec&) const = default; };
  template <class It, class T> It find(It, It last, const T&) { return last; }
}

void f(std::vector<lib::Rec>& v) {
  using std::find;
  find(v.begin(), v.end(), lib::Rec{1});
}
```

A. It calls `std::find`, because the using-declaration takes priority
B. It calls `lib::find`, because ADL results are preferred
C. It calls `std::ranges::find`
D. It is ill-formed: the call is ambiguous between `std::find` and `lib::find`

**Answer (D):** It is ill-formed: the call is ambiguous between `std::find` and `lib::find`

**Why:** `std::find` is a function template, so ADL still runs, and `lib` is an associated namespace through the template argument `lib::Rec` of the vector's iterator type. Both templates have the same parameter pattern, neither is more specialized, and the call is ambiguous. Had the using-declaration named the niebloid `std::ranges::find`, ordinary lookup would find an object, ADL would be suppressed, and the call would be unambiguous.

### Question 5 [tricky] ([range.access.begin], [range.access.end], [range.range])

Does this compile?

```cpp
#include <ranges>

namespace lib {
  struct Both {
    int d[2]{};
    int* begin() { return d; }
    int* end() { return d + 2; }
  };
  int* begin(Both&) = delete;
  int* end(Both&) = delete;
}

static_assert(std::ranges::range<lib::Both>);
```

A. Yes: `ranges::begin` and `ranges::end` use the members and never reach the ADL step
B. No: ADL finds the deleted functions, which makes `ranges::begin` ill-formed
C. No: the member and the free function make the call ambiguous
D. Yes, but only because deleted functions are ignored by overload resolution

**Answer (A):** Yes: `ranges::begin` and `ranges::end` use the members and never reach the ADL step

**Why:** `ranges::begin` tries its strategies in order: array, then a valid member `t.begin()` returning an iterator, then ADL-only `begin(t)`. The member is valid here, so the deleted free functions are never looked at. The last option is wrong on its own terms: deleted functions do take part in overload resolution, and selecting one makes the expression invalid, which is exactly what would happen if there were no members.

### Question 6 [tricky] ([concept.swappable], [customization.point.object])

What happens with this call?

```cpp
#include <concepts>

int main() {
  int x[2]{1, 2}, y[3]{3, 4, 5};
  std::ranges::swap(x, y);
}
```

A. It swaps the first two elements and leaves `y[2]` alone
B. It is ill-formed: no strategy of `ranges::swap` applies
C. It compiles but has undefined behavior
D. It swaps what the two names refer to

**Answer (B):** It is ill-formed: no strategy of `ranges::swap` applies

**Why:** `ranges::swap` tries an ADL `swap`, which needs a class or enumeration argument; then `swap_ranges` for lvalue arrays of equal extent; then a move-based exchange of two lvalues of the same movable type. `int[2]` and `int[3]` fail all three, so the call operator is not viable and the call does not compile. Arrays are never swapped partially.

### Question 7 [standardese] ([namespace.std])

In C++20 and later, what is the status of this explicit specialization?

```cpp
#include <utility>

namespace lib { struct Widget { int id; }; }

template <>
void std::swap<lib::Widget>(lib::Widget& a, lib::Widget& b) noexcept {
  std::swap(a.id, b.id);
}
```

A. Allowed, because it depends on a program-defined type
B. Ill-formed: a diagnostic is required
C. Allowed only if it is declared `noexcept`
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** Since C++20 (P0551), [namespace.std] allows programs to specialize standard library class templates for program-defined types, but no longer function templates, so this declaration has undefined behavior. Until C++17 it was permitted, which is why the first option is tempting. Compilers accept it silently; put a hidden friend `swap` in the class instead.

### Question 8 [standardese] ([namespace.std], [meta.rqmts], [range.range])

`MyType` and `MyView` are program-defined types that meet the relevant requirements. Which of these declarations has undefined behavior?

A. `template<> struct std::hash<MyType> { std::size_t operator()(const MyType&) const; };`
B. `template<> struct std::is_integral<MyType> : std::true_type {};`
C. `template<> inline constexpr bool std::ranges::enable_borrowed_range<MyView> = true;`
D. `template<> struct std::tuple_size<MyType> : std::integral_constant<std::size_t, 2> {};`

**Answer (B):** `template<> struct std::is_integral<MyType> : std::true_type {};`

**Why:** [namespace.std] and [meta.rqmts] forbid specializing the templates in `<type_traits>`, with `common_type` and `basic_common_reference` as the only exceptions, so specializing `is_integral` is undefined behavior. `std::hash` is a class template specialized for a program-defined type, which is allowed. `enable_borrowed_range` is one of the variable templates the standard explicitly lets programs specialize for their own types. Specializing `std::tuple_size`, as for structured bindings, is an ordinary class template specialization and is allowed too.
