You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`std::expected` (C++23) is a vocabulary type for functions that can either produce a value (success) or a well-defined recoverable error (failure) without throwing. It generalizes the intent behind `std::optional`: instead of “value or nothing”, you get “value *or*error payload”.
12
+
**How to handle errors in C++ has been a constant point of debate.** Do you use exceptions, error code, out-parameters or return nullptrs on failure? And how do you convey information on the nature of the failure? With C++17 we got `std::optional` for "value or nothing" semantics, but it lacks error context. [C++23 - finally - introduces `std::expected`](https://en.cppreference.com/w/cpp/utility/expected.html), a type that encapsulates either a value or an error, making error handling explicit and composable. Let's explore how `std::expected` can improve your C++ code.
13
13
14
-
Key points:
15
-
- Success path is explicit (`expected<T,E>` holds `T`)
16
-
- Failure path is explicit (holds `E`)
17
-
- Zero-cost access in the success case (no heap)
18
-
- Works alongside (not instead of) exceptions
19
-
- Encourages documenting failure modes via the error type
14
+
## `std::expected` in a nutshell
20
15
21
-
## Basic Form
16
+
Semantically, `std::expected<T, E>` is a returnable type that can either hold a value of type `T` (indicating success) or an error of type `E` (indicating failure). This makes it clear to the caller that a function can fail and provides a structured way to handle that failure.
- `*r` / `r.value()` gives the value (latter throws `bad_expected_access` if no value)
52
-
- `r.error()` yields the error object (only if !r)
53
-
54
-
## Why Not Just std::optional?
55
-
`std::optional<T>` only distinguishes “present” vs “absent”. You must invent an external channel (logs, out-params, magic enums) for error context. `std::expected<T,E>` bakes the error representation into the type signature, making intent self-documenting and enabling composition.
0 commit comments