In a C++23 modernization, what do std::expected and deducing this each replace, and when would you reach for them?
answer
- value or typed error
- error visible in the signature
- and_then, transform, or_else
- explicit object parameter this Self
- one body for const and non-const
basics
~20 sstd::expected<T, E> returns either a value or a typed error, replacing error codes with out-parameters and ad hoc result structs where failure is normal. Deducing this makes the object an explicit parameter, replacing duplicated const and non-const overloads and much CRTP boilerplate.
solid answer
~40 s**`std::expected<T, E>`** (`<expected>`) holds a `T` or an `E`. A parser returns `std::unexpected(ParseError::empty)` on failure and the value otherwise; the caller tests it, reads `error()`, or chains `and_then`, `transform` and `or_else`. It replaces `bool f(T& out)` signatures, sentinel values and exceptions for *expected* failures, and keeps the error type in the signature; `value()` throws `std::bad_expected_access` when there is no value, while `*e` without a value is undefined behaviour. **Deducing this** — an explicit object parameter, `template <class Self> auto&& get(this Self&& self)` — lets one member function body serve `const`, non-`const`, lvalue and rvalue objects, replacing overload quadruplets. It also lets a lambda recurse and simplifies CRTP. Such members cannot be `virtual` or `static`.
code
cpp · 34 lines#include <expected>
#include <print>
#include <string>
#include <charconv>
#include <system_error>
enum class ParseError { empty, not_a_number };
std::expected<int, ParseError> parse_port(const std::string& s) {
if (s.empty()) return std::unexpected(ParseError::empty);
int value = 0;
auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value);
if (ec != std::errc{}) return std::unexpected(ParseError::not_a_number);
return value;
}
struct Config {
std::string host = "localhost";
// C++23 deducing this: one body serves const and non-const objects
template <typename Self>
auto&& host_ref(this Self&& self) { return std::forward<Self>(self).host; }
};
int main() {
for (std::string in : {"8080", "", "http"}) {
auto port = parse_port(in);
if (port) std::println("port {}", *port);
else std::println("error {}", static_cast<int>(port.error()));
}
Config c;
const Config& cc = c;
c.host_ref() = "example.test";
std::println("{}", cc.host_ref());
}go deeper
Know that std::expected holds a value or an error and that you check it before reading; know deducing this lets one member function serve const and non-const objects.
Explain value() versus operator*, the monadic and_then and transform, and how this Self&& deduces the object's type and value category.
Place them in a real design: which API boundaries return expected, where exceptions stay, and which duplicated overloads or CRTP bases deducing this removed.
Set the error-handling convention: when a team uses expected, exceptions or error codes, and how mixed styles are kept from leaking across module boundaries.
## Two C++23 features that change everyday design Both features answer long-standing complaints. `std::expected` gives C++ a standard **error-as-value** type; **deducing this** removes duplicated member functions. In a modernisation story they show up in different places: `std::expected` at API boundaries where failure is normal, deducing this inside class implementations. ## std::expected: errors as values `std::expected<T, E>` contains either a value of type `T` or an error of type `E`, never neither. The pieces: - construct the error with **`std::unexpected(err)`**; return a `T` for success; - test with `has_value()` or `if (result)`; - read with `*result`, `result->member`, **`value()`**, `error()` or `value_or(fallback)`; - chain with the **monadic** members `and_then` (next step returns an `expected`), `transform` (next step returns a plain value), `or_else` (handle or replace the error) and `transform_error`. What it replaces: | Before | Problem | With `std::expected` | |---|---|---| | `bool parse(const std::string&, int& out)` | out-parameter, the error reason is lost | `std::expected<int, ParseError> parse(...)` | | `std::optional<int>` | no reason for the failure | the error carries the reason | | `-1` or another sentinel | easy to ignore, steals a valid value | the type forces the caller to look | | exceptions for routine failures | invisible in the signature, costly when thrown often | the error type is part of the signature | Two access rules matter. **`value()`** throws `std::bad_expected_access<E>` when the object holds an error. **`operator*`** and `operator->` have a precondition that a value is present; violating it is undefined behaviour in C++23. Exceptions remain the better tool for failures that are rare and must cross many layers; `std::expected` fits failures the immediate caller is expected to handle, such as parsing, lookups and validation. ## Deducing this: the object as a parameter Before C++23, a member function received its object implicitly, and its `const` and reference qualifiers were fixed per overload. A getter that should return `T&`, `const T&` or `T&&` depending on the object needed up to four nearly identical bodies. C++23 lets the first parameter be an **explicit object parameter**, marked with `this`: ```cpp struct Config { std::string host; template <class Self> auto&& host_ref(this Self&& self) { return std::forward<Self>(self).host; } }; ``` `Self` is deduced from the object the function is called on, so one template serves every combination. Further uses: 1. **Recursive lambdas**: `auto fib = [](this auto self, int n) -> int { return n < 2 ? n : self(n - 1) + self(n - 2); };` 2. **CRTP without the base template parameter**: a base-class member with `this auto& self` sees the derived type directly. 3. **Pass the object by value** when it is small: `this Point self`. The rules: an explicit object member function cannot be `static` or `virtual`, and cannot carry `const` or `&` qualifiers after the parameter list — the explicit parameter's type says all of that. Inside the body there is no implicit `this`; members are reached through `self`. ## A worked chain The monadic members let a sequence of fallible steps read top to bottom, with the error short-circuiting the rest: ```cpp // C++23; runs with Apple clang 21 and libc++ std::expected<std::string, Err> non_empty(std::string s); std::expected<std::string, Err> short_enough(std::string s); auto name = non_empty(input) .and_then(short_enough) // next step returns expected .transform([](std::string s) { return s + "-svc"; }) // next step returns a value .value_or("rejected"); ``` For `"deploy"` the result is `deploy-svc`; for an empty or over-long input the first failing step's error passes through the remaining steps untouched and `value_or` yields `rejected`. The same flow written with out-parameters needs a nested `if` per step. ## When to reach for them 1. Use **`std::expected`** for operations whose failure is part of normal control flow and is handled close to the call. 2. Keep **exceptions** for rare failures that must unwind far, and for constructors. 3. Use **deducing this** where you were about to write `const` and non-`const` twins, a recursive lambda through `std::function`, or a CRTP base. 4. Check the **toolchain**: the feature-test macros are `__cpp_lib_expected` (`202211L` with the monadic members) and `__cpp_explicit_this_parameter`. Apple clang 21 with libc++ compiles both in `-std=c++23` mode.
- Why is std::optional a weaker choice than std::expected for a parser's return type?`std::optional<int>` can say only that parsing failed, not why: empty input, a non-numeric character and an out-of-range value all collapse into `std::nullopt`. `std::expected<int, ParseError>` carries the reason, so the caller can report it or react differently. Use `optional` when absence is the only failure and needs no explanation.
- Why can't an explicit object member function be virtual?C++23 forbids it: a member declared with an explicit object parameter shall not be `virtual` or `static`. One practical reason: such functions are usually templates on the object's type, and a function template cannot be virtual either. Where runtime dispatch is needed, keep an ordinary virtual function; use deducing this for compile-time variations on the object's type and value category.
std::expected is a delivery box that always arrives: it holds either the item you ordered or a note saying why it could not be sent, and you must open it to find out which.
- Dereferencing an empty std::expected throws an exception.
- std::expected should replace every exception in a codebase.
- Deducing this makes member functions dynamically dispatched.
- std::optional already carries the reason for a failure.
- An explicit object member function can still use the implicit this pointer.
Assumes C++23: std::expected and explicit object parameters are C++23 features; checked with Apple clang 21 in -std=c++23 mode.