# Vocabulary types and std::format

> Value-semantic sum types, type-erased callables with const and move-only correctness, and compile-time checked text formatting in modern C++.

- **Source:** C++ Atlas (https://cppatlas.com/topics/vocabulary-types-and-format)
- **Track:** Library utilities
- **Estimated reading time:** 11 minutes
- **ISO C++ clauses:** [optional] (https://eel.is/c++draft/optional), [variant] (https://eel.is/c++draft/variant), [any] (https://eel.is/c++draft/any), [func.wrap.move] (https://eel.is/c++draft/func.wrap.move), [format.fmt.string] (https://eel.is/c++draft/format.fmt.string)
- **cppreference links:** [std::optional](https://en.cppreference.com/w/cpp/utility/optional), [std::variant](https://en.cppreference.com/w/cpp/utility/variant), [std::visit](https://en.cppreference.com/w/cpp/utility/variant/visit2), [std::any](https://en.cppreference.com/w/cpp/utility/any), [std::move_only_function](https://en.cppreference.com/w/cpp/utility/functional/move_only_function), [std::format](https://en.cppreference.com/w/cpp/utility/format/format), [std::print](https://en.cppreference.com/w/cpp/io/print)
- **Prerequisites:** copy-and-move, optional-expected-and-error-codes

Modern standard C++ replaces sentinel integers (`-1`), `void*` user-data pointers, and stateful `std::ostream` manipulators with **vocabulary types**: value-semantic abstractions that encode presence, alternatives, callable ownership, and formatting rules directly in the type system.

> **Mental model.** `std::optional<T>` represents `T + 1` states, `std::variant<Ts...>` represents a closed sum `T1 + T2 + ...`, and `std::any` represents an open type-erased slot. All three store small objects inline without touching the heap when possible, preserving value semantics.

## Algebraic types: optional, variant, and any

`std::optional<T>` models an object that may or may not exist using aligned inline storage for `T` plus a `bool` engaged flag—zero heap allocation. Calling `.value()` throws `std::bad_optional_access` when empty, whereas `*opt` and `opt->` are unchecked (undefined behavior if empty). C++23 adds monadic operations—`.and_then()`, `.transform()`, and `.or_else()`—so pipelines avoid nested `if (opt)` pyramids:

```cpp
#include <optional>
#include <string_view>

std::optional<int> parse_port(std::string_view text) {
    if (text == "443") return 443;
    return std::nullopt;
}

int resolve_port(std::optional<std::string_view> env_value) {
    return env_value
        .and_then(parse_port)
        .transform([](int port) { return port + 1000; })
        .or_else([]() -> std::optional<int> { return 8080; })
        .value();
}
```

`std::variant<Ts...>` is a type-safe discriminated union sized to the maximum size and alignment of its alternatives plus a compact index tag. Unlike `std::optional`, a default-constructed `std::variant` initializes its **first** alternative `T0` (wrap `std::monostate` as `T0` when an empty state is desired or `T0` is not default-constructible).

While `std::variant` normally always holds one active alternative, it can enter a rare degenerate state where `v.valueless_by_exception()` is `true` (`v.index() == std::variant_npos`). That happens only if an exception is thrown *during* type-changing assignment or `emplace()` after destroying the old alternative and before completing construction of the new one.

`std::any` trades a closed alternative list for open type erasure: it stores any `CopyConstructible` type, typically using a Small Buffer Optimization (SBO) for small nothrow-movable objects and allocating on the heap for larger ones. Access via `std::any_cast<T>(&a)` returns `nullptr` on type mismatch, whereas `std::any_cast<T>(a)` throws `std::bad_any_cast`.

## Exhaustive visitation and the overloaded pattern

Reading a `std::variant` with `std::get_if<T>(&v)` works for one case, yet `std::visit` enforces **compile-time exhaustiveness** across every alternative. The standard idiom combines a variadic inheritance wrapper `overloaded` with `using Ts::operator()...`:

```cpp
#include <cstddef>
#include <string>
#include <variant>

template <class... Ts>
struct overloaded : Ts... {
    using Ts::operator()...;
};

std::size_t payload_score(const std::variant<int, std::string>& item) {
    return std::visit(overloaded{
        [](int n) -> std::size_t { return static_cast<std::size_t>(n); },
        [](const std::string& s) -> std::size_t { return s.size(); },
    }, item);
}
```

Since C++20, aggregate Class Template Argument Deduction deduces `overloaded` without an explicit deduction guide (add `template <class... Ts> overloaded(Ts...) -> overloaded<Ts...>;` only if targeting C++17). Note that `std::visit` checks `valueless_by_exception()` internally and throws `std::bad_variant_access` if any visited variant is valueless.

> **Pitfall.** Avoid writing a catch-all `[](const auto&) {}` arm inside `overloaded` unless deliberate fallback behavior is required: a generic lambda silently swallows newly added variant alternatives and defeats compile-time exhaustiveness checking.

## Callable wrappers: std::function vs. std::move_only_function

For over a decade, `std::function<R(Args...)>` was the default type-erased callback wrapper, yet it carries three structural flaws:

1. **Copy requirement:** `std::function` demands a `CopyConstructible` target, rejecting lambdas that capture `std::unique_ptr`, `std::jthread`, or move-only futures.
2. **Broken `const` propagation:** `std::function::operator()` is always `const`-qualified regardless of whether the wrapped callable mutates captured state. Calling a `const std::function` can mutate `[x = 0]() mutable { return ++x; }` silently.
3. **RTTI and throwing empty checks:** `std::function` stores RTTI for `.target_type()` and checks for null on every invocation to throw `std::bad_function_call`.

C++23 `std::move_only_function<Sig>` fixes all three. Its template signature encodes cv-qualifiers, ref-qualifiers (`&` / `&&`), and `noexcept` directly into the wrapper interface:

```cpp
#include <functional>
#include <memory>
#include <utility>

int run_task() {
    auto token = std::make_unique<int>(42);
    std::move_only_function<int() const noexcept> fn =
        [t = std::move(token)]() noexcept { return *t; };

    const auto& readonly_fn = fn;
    return readonly_fn();
}
```

Without `const` in `std::move_only_function<int()>`, calling through `const auto&` fails to compile; with `noexcept` in the signature, only `noexcept` callables bind and calling `fn()` is itself `noexcept`. Unlike `std::function`, invoking an empty `std::move_only_function` is undefined behavior rather than throwing, eliminating a conditional check and dropping RTTI overhead.

> **Standardese.** `[func.wrap.func]` permits `std::function::operator() const` to invoke non-`const` callable objects without propagating `const` correctness. `[func.wrap.move]` resolves this in C++23 by encoding the exact `const`, `&`/`&&`, and `noexcept` qualifiers in the template parameter of `std::move_only_function`.

## Compile-time checked std::format and std::print

C++20 `<format>` and C++23 `<print>` replace both type-unsafe `printf` varargs and verbose stateful `std::ostream` manipulators (`std::hex`, `std::setw` leaking across statements).

`std::format` achieves safety without runtime format parsing bugs by accepting `std::format_string<Args...>`, whose constructor is `consteval`:

```cpp
#include <format>
#include <print>
#include <string>
#include <vector>

struct Point {
    int x;
    int y;
};

template <>
struct std::formatter<Point> {
    constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
    auto format(const Point& p, std::format_context& ctx) const {
        return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
    }
};

void emit_report() {
    Point origin{3, 4};
    std::vector<int> samples{10, 20, 30};
    std::string text = std::format("pt={} samples={}", origin, samples);
    std::println("{}", text);
}
```

Because `format_string` runs at compile time, passing `"{:d}"` for a `std::string` or mismatched placeholder counts fails compilation immediately. When a format pattern genuinely comes from runtime configuration, opt in explicitly with `std::vformat(fmt, std::make_format_args(arg1, arg2))`—noting that after defect report P2905R2, `std::make_format_args` requires **lvalue** arguments so the returned `format_args` object cannot dangle on temporaries.

C++23 also adds range formatting directly (`std::format("{}", vec)`) and `<print>` (`std::print`, `std::println`), which write directly to `FILE*` or `stdout` without intermediate `std::string` heap allocations and support UTF-8 console output cleanly.

> **Pitfall.** Calling `std::format(runtime_string, x)` fails to compile because `std::format_string<Args...>` requires a compile-time constant string. Use `std::vformat(runtime_string, std::make_format_args(x))` with named lvalue variables when the format string is dynamic.

## Choosing the right utility abstraction

Matching each tool to its ownership and dispatch trade-offs prevents accidental heap allocations, broken `const` invariants, and unchecked runtime formatting errors.

| Type | Heap allocation | Copyable vs move-only | Failure or empty behavior | Best use case |
| --- | --- | --- | --- | --- |
| `std::optional<T>` | Never (inline) | Inherits from `T` | `.value()` throws; `*opt` is UB | Nullable values and optional fields |
| `std::variant<Ts...>` | Never (inline) | Inherits from `Ts...` | `std::get` throws; may go valueless on throw | Closed AST/state machine alternatives |
| `std::any` | SBO then heap | Requires `CopyConstructible` | `any_cast` throws or returns `nullptr` | Open heterogeneous property bags |
| `std::function<Sig>` | SBO then heap | Requires `CopyConstructible` | Empty call throws `bad_function_call` | Legacy copyable callbacks |
| `std::move_only_function<Sig>` | SBO then heap | Move-only (`const`/`noexcept` safe) | Empty call is UB | Modern single-owner tasks and handlers |

## What to remember

- Use `std::optional` monadic methods (`and_then`, `transform`, `or_else`) to chain nullable computations cleanly without heap allocation.
- Prefer `std::visit(overloaded{...}, v)` over `get_if` chains so the compiler enforces handling of every `std::variant` alternative.
- Switch callbacks from `std::function` to C++23 `std::move_only_function` to accept `std::unique_ptr` captures and preserve `const` and `noexcept` qualifiers.
- `std::format` and `std::print` validate format strings at compile time via `consteval` `std::format_string`; use `std::vformat` with lvalue arguments only when runtime format strings are unavoidable.

## Concept Map Outline

- **Vocabulary types and format:** Modern C++ encodes optionality, sum types, qualified callables, and checked formatting directly in types.
  - **std::optional values:** Stores T inline plus an engaged boolean with zero heap allocation.
    - **Checked vs unchecked access:** Calling value() throws bad_optional_access while operator* assumes engagement.
    - **C++23 monadic ops:** and_then, transform, and or_else chain optional steps cleanly.
      - **Flat error pipelines:** Monadic combinators forward nullopt cleanly without nested conditional branches.
  - **std::variant sum types:** Discriminated union sized to the largest alternative plus an active index.
    - **overloaded and std::visit:** Variadic lambda inheritance enforces exhaustive compile-time dispatch across alternatives.
      - **Avoid catch-all arms:** Skipping generic auto lambdas preserves compiler errors on new alternatives.
    - **valueless_by_exception:** Occurs only if type-changing assignment throws after destroying the old alternative.
  - **std::any open erasure:** Type-erased container storing any CopyConstructible value via SBO or heap.
    - **any_cast pointer vs value:** Pointer any_cast returns nullptr on mismatch while value cast throws bad_any_cast.
  - **Callable wrappers:** Type-erased invokables differ sharply in copyability and const propagation.
    - **std::function pitfalls:** Requires CopyConstructible targets and breaks const correctness on mutable lambdas.
    - **move_only_function:** C++23 wrapper supports unique_ptr captures and honors const and noexcept qualifiers.
      - **No empty-call overhead:** Calling an empty move_only_function is UB, removing branches and RTTI.
  - **std::format and std::print:** Type-safe formatting checked at compile time with zero stream state.
    - **consteval format_string:** Rejects mismatched placeholders at compile time; dynamic strings require std::vformat.
      - **Lvalues in make_format_args:** Defect report P2905R2 restricts make_format_args to lvalues to avoid dangling.
    - **Custom std::formatter:** Specialize parse and format to integrate user types and C++23 std::println.

## Standardese Quiz Questions

### Question 1 [warmup] ([variant.ctor], [variant.monostate])

Why does std::variant<NonDefault, int> fail to default-construct, and what standard helper fixes it?

```cpp
struct NonDefault { explicit NonDefault(int) {} };
std::variant<NonDefault, int> v;
```

A. std::variant default-constructs its first alternative (NonDefault); placing std::monostate first makes the variant default-constructible
B. std::variant requires every alternative to be default-constructible
C. std::variant always starts empty like std::optional
D. std::variant selects int automatically when the first alternative lacks a default constructor

**Answer (A):** std::variant default-constructs its first alternative (NonDefault); placing std::monostate first makes the variant default-constructible

**Why:** A default-constructed std::variant constructs its zero-indexed alternative. If the first type is not default-constructible, std::variant's default constructor is deleted; putting std::monostate as the first alternative provides a lightweight empty initial state.

### Question 2 [warmup] ([func.wrap.func.con], [func.wrap.move])

Why does storing a lambda that captures std::unique_ptr<int> fail with std::function<int()> but succeed with std::move_only_function<int()>?

```cpp
auto p = std::make_unique<int>(7);
std::move_only_function<int()> f = [p = std::move(p)] { return *p; };
```

A. std::function cannot store lambdas with captures at all
B. std::function requires stored callables to be CopyConstructible, whereas std::move_only_function requires only MoveConstructible
C. std::move_only_function stores pointers without calling destructors
D. std::function only works with function pointers

**Answer (B):** std::function requires stored callables to be CopyConstructible, whereas std::move_only_function requires only MoveConstructible

**Why:** std::function mandates CopyConstructible targets because std::function itself is copyable. C++23 std::move_only_function drops copyability, enabling move-only captures such as std::unique_ptr.

### Question 3 [tricky] ([func.wrap.func.inv], [func.wrap.move.inv])

What happens when calling f() through const std::function<int()>& vs const std::move_only_function<int()>& wrapping a mutable lambda?

```cpp
const std::function<int()> a = [n = 0]() mutable { return ++n; };
const std::move_only_function<int()> b = [n = 0]() mutable { return ++n; };
```

A. Both fail to compile because calling a mutable lambda through const is ill-formed
B. Both compile and increment n on every call
C. a compiles and mutates n despite being const; b fails to compile because std::move_only_function<int()> does not declare a const operator()
D. b compiles while a throws std::bad_function_call

**Answer (C):** a compiles and mutates n despite being const; b fails to compile because std::move_only_function<int()> does not declare a const operator()

**Why:** std::function::operator() is always const-qualified regardless of the wrapped callable, silently allowing mutation through a const std::function. std::move_only_function honors qualifiers in its signature: const invocations require std::move_only_function<int() const>.

### Question 4 [tricky] ([format.arg.store])

Why does std::vformat(fmt, std::make_format_args(42)) fail to compile under C++20/23 after DR P2905R2?

```cpp
std::string fmt = "{}";
auto s = std::vformat(fmt, std::make_format_args(42));
```

A. std::vformat does not accept integers
B. std::format_args only accepts std::string arguments
C. std::make_format_args returns void
D. std::make_format_args takes Args&... (lvalue references) to prevent storing dangling pointers to temporaries inside format_args

**Answer (D):** std::make_format_args takes Args&... (lvalue references) to prevent storing dangling pointers to temporaries inside format_args

**Why:** Defect report P2905R2 changed std::make_format_args from forwarding references (Args&&...) to lvalue references (Args&...) so callers cannot accidentally bind temporaries like 42 or std::string{} whose lifetime ends before std::vformat runs.

### Question 5 [standardese] ([variant.status], [variant.assign])

Under what circumstance can std::variant::valueless_by_exception() become true?

A. Whenever a variant holds std::monostate
B. When an exception is thrown during type-changing assignment or emplace() after the previous alternative was destroyed and before the new one finishes constructing
C. Whenever a variant is moved from
D. Whenever std::get<T> fails with std::bad_variant_access

**Answer (B):** When an exception is thrown during type-changing assignment or emplace() after the previous alternative was destroyed and before the new one finishes constructing

**Why:** According to [variant.status], a variant never becomes valueless during normal construction or moves; it becomes valueless_by_exception() only if an exception interrupts a type-changing assignment or emplace() between destroying the old value and constructing the replacement.

### Question 6 [standardese] ([func.wrap.move.inv], [func.wrap.func.inv])

What distinguishes invoking an empty std::move_only_function from invoking an empty std::function?

A. Calling an empty std::move_only_function is undefined behavior, whereas calling an empty std::function throws std::bad_function_call
B. Both throw std::bad_function_call
C. Calling an empty std::move_only_function returns a default-constructed R{}
D. std::move_only_function cannot be default-constructed or empty

**Answer (A):** Calling an empty std::move_only_function is undefined behavior, whereas calling an empty std::function throws std::bad_function_call

**Why:** Under [func.wrap.move.inv], invoking an empty std::move_only_function has a precondition that *this is non-empty (undefined behavior if violated), avoiding the branch and exception path mandated by std::function in [func.wrap.func.inv].
