Skip to content
Tutorials Center
My learning

Topics

Lesson 103 of 171 ยท The Standard Library (STL)

std::optional, std::variant, std::any and std::expected

Learn the C++ vocabulary types - std::optional with value_or and and_then, std::variant with std::visit, std::any, and std::expected for error handling in C++23.

Some values don't fit neatly into a single type. A search may find a user or find nothing. A JSON value may be a number, a string or a list. A parsing function may produce a result or a reason why it failed. Older C++ code handled these cases with sentinel values (-1, nullptr, an empty string), out-parameters, unions with a separate tag, or void*. All of them are easy to misuse, and the compiler can't help.

Modern C++ has four vocabulary types that express these situations directly and safely: std::optional<T> (C++17) for "a T or nothing", std::variant<A, B, ...> (C++17) for "exactly one of these types", std::any (C++17) for "a value of any type", and std::expected<T, E> (C++23) for "a T or an error E". In this lesson you'll learn each one, the C++23 monadic operations that let you chain them without nested ifs, std::visit with the overloaded-lambdas trick, and how to choose between them.

std::optional: maybe a value

std::optional<T> (header <optional>) either contains a T or is empty. The empty state is spelled std::nullopt. The value is stored inside the optional object, with no heap allocation, so sizeof(std::optional<int>) is typically 8: the int plus a flag, padded.

The essential operations:

  • if (opt) or opt.has_value() checks for a value.
  • *opt and opt->member access it. Like a raw pointer, this is unchecked: dereferencing an empty optional is undefined behavior.
  • opt.value() is checked: it throws std::bad_optional_access if empty.
  • opt.value_or(fallback) returns the value or a fallback.
  • opt = value, opt.emplace(args...), opt.reset() and opt = std::nullopt change it.
C++ Returning maybe-a-value with optional

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Use optional for return values that may legitimately be absent ("not found", "no config entry"), for optional members, and for lazily computed values. Don't use it when the absence needs an explanation; that's what std::expected is for. A few rules:

  • Comparing an optional with a value works (opt == 3 is false when empty), and empty optionals compare less than any value.
  • std::optional<T&> isn't allowed before C++26; use T* or std::optional<std::reference_wrapper<T>> for "maybe a reference".
  • Taking const std::optional<T>& as a parameter forces callers to construct an optional (a copy of their T). For optional inputs, an overload or a const T* parameter is often better.

Monadic operations (C++23)

Code that works with several optionals in a row quickly becomes a staircase of if (a) { if (b) { ... } }. C++23 adds three member functions that chain steps instead:

  • opt.transform(f): if there's a value, returns optional{f(value)}; otherwise an empty optional of the new type.
  • opt.and_then(f): f itself returns an optional; use it for steps that can fail.
  • opt.or_else(f): if empty, calls f to produce a replacement optional.
C++ Chaining optionals with and_then and transform

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Each step runs only if the previous one produced a value; the first empty result short-circuits the rest of the chain. Notice that "invalid input" doesn't tell you why: abc failed to parse while -7 failed validation. When you need that distinction, switch to std::expected, which has the same operations.

std::variant: one of several types

std::variant<A, B, C> (header <variant>) holds exactly one value whose type is one of the listed alternatives. It's a type-safe union: it remembers which alternative is active, constructs and destroys it properly, and refuses to let you read the wrong one. Like optional, it stores the value inline, so its size is the largest alternative plus a small index.

  • v.index() returns the zero-based index of the active alternative.
  • std::holds_alternative<T>(v) tests for a type.
  • std::get<T>(v) or std::get<I>(v) returns the value, or throws std::bad_variant_access if another alternative is active.
  • std::get_if<T>(&v) returns a pointer to the value, or nullptr: the non-throwing check-and-access.
  • A default-constructed variant holds a default-constructed first alternative. If that type has no default constructor, put std::monostate first as an explicit "empty" state.

std::visit and the overloaded pattern

The best way to work with a variant is std::visit(visitor, v), which calls the visitor with whatever alternative is active. The visitor must accept every alternative, so the compiler tells you if you forget one, something a chain of if (holds_alternative...) never does. A popular helper builds a visitor from several lambdas:

C++
template <typename... Fs>
struct overloaded : Fs... { using Fs::operator()...; };

It inherits from all the lambdas and pulls in each one's operator(), so normal overload resolution picks the right lambda for each type. (C++17 needed an extra deduction guide line; C++20's aggregate deduction makes it unnecessary.)

C++ Shapes as a variant, processed with std::visit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The const auto& lambda in describe is a generic catch-all: overload resolution prefers the exact Circle lambda for circles and uses the generic one for everything else.

variant versus inheritance

A variant is a closed set of types known at compile time; a class hierarchy with virtual functions is an open set that new code can extend. Variants need no heap allocation, no pointers and no virtual destructor, and adding a new operation (another visit) is easy. Hierarchies make adding a new type easy. Parsers, state machines, message types and AST nodes are classic variant territory.

std::any: a value of any type

std::any (header <any>) can hold a single value of any copyable type, and you can change the type at any time. You get it back with std::any_cast<T>, which must name the exact stored type:

  • std::any_cast<T>(a) returns a copy, or throws std::bad_any_cast on a type mismatch.
  • std::any_cast<T>(&a) returns a T*, or nullptr on a mismatch.
  • a.type() returns a std::type_info, a.has_value() checks for emptiness, and a.reset() empties it.
C++ A property bag with std::any

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::any_cast<long> on an int fails: there's no conversion, only exact type matches. std::any may allocate on the heap for larger types (small types use an internal buffer), and every access needs a type check. It's useful at boundaries where types truly aren't known in advance, such as plugin systems or generic property storage. If you can list the possible types, a std::variant is safer and faster.

std::expected: a value or an error (C++23)

std::expected<T, E> (header <expected>) holds either a successful T or an error E. It's like an optional that explains itself. You return a value normally, and an error wrapped in std::unexpected(error):

  • if (result) / result.has_value() checks for success; *result and -> access the value unchecked.
  • result.error() returns the error (only valid when there's no value).
  • result.value() throws std::bad_expected_access<E> if it holds an error.
  • value_or, and_then, transform, or_else and transform_error work like optional's monadic operations, carrying the error through the chain.
C++ Parsing with std::expected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Unlike exceptions, std::expected makes failure part of the function's type: callers can see that it may fail and must deal with the error to reach the value. There's no hidden control flow and no cost beyond returning a slightly larger object, which is why it's popular in performance-sensitive code and in codebases that disable exceptions. Exceptions remain the better tool for rare errors that must travel many layers up, and for constructors, which can't return a value. The trade-offs are covered in Error Handling Without Exceptions and Exceptions.

std::expected<void, E> is valid for operations that succeed with no value, such as "save the file".

Choosing a vocabulary type

Situation Use
A value that may be absent, and the reason doesn't matter std::optional<T>
A value or a reason for failure std::expected<T, E>
One of a fixed, known set of types std::variant<Ts...>
A value of a type not known until run time std::any (rarely)
One of several types that other code must be able to extend A class hierarchy with virtual functions

All four store their contents by value, clean up automatically, and have well-defined copy and move behavior. That alone makes them far safer than the sentinel values, tagged unions and void* they replace.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. std::optional<int> o; std::println("{}", o.value_or(9)); What is printed?

    A default-constructed optional is empty, so value_or returns the fallback 9. Only value() throws, and only *o is undefined behavior when empty.
  2. 2. What happens when you call *opt on an empty std::optional?

    operator* and operator-> don't check, just like dereferencing a pointer. Use value() for a checked access or test the optional first.
  3. 3. Why is std::visit with a visitor that handles every alternative safer than a chain of holds_alternative checks?

    The visitor must be callable with every alternative, so adding a new type to the variant produces compile errors at every visit that doesn't handle it.
  4. 4. std::any a = 42; auto x = std::any_cast<long>(a); What happens?

    any_cast requires the exact stored type. The stored type is int, so casting to long throws; the pointer form would return nullptr instead.
  5. 5. In parse(text).and_then(validate).transform(format), parse returns a std::expected holding an error. What happens next?

    and_then and transform only run on a value. An error short-circuits the chain and is carried to the end unchanged; transform_error and or_else are the operations that act on errors.

Summary

  • std::optional<T> holds a T or nothing (std::nullopt), inline with no allocation. Check before *, use value() for checked access and value_or for fallbacks.
  • C++23 adds transform, and_then and or_else to chain optional steps without nested ifs; std::expected has the same operations plus transform_error.
  • std::variant<Ts...> is a type-safe union. Read it with std::visit (with the overloaded lambda helper), std::get_if, or std::get, which throws on the wrong type.
  • std::any holds any copyable type and needs an exact-type any_cast; prefer a variant when you can list the types.
  • std::expected<T, E> (C++23) returns a value or an error with std::unexpected, making failure visible in the type without exceptions.

Next: std::bitset, a fixed-size set of bits with handy operations for flags and masks.