In C++23, how do and_then, transform, or_else and transform_error chain std::expected steps, and what must each callable return?
answer
- two on the value, two on the error
- one callable already returns a wrapper
- the error type must match
- recovery happens on the error path
basics
~20 sand_then calls f(value) and f must return an expected with the same error type; transform wraps a plain result; or_else calls f(error) and must return an expected with the same value type; transform_error maps the error. Errors skip value steps.
solid answer
~40 sC++23 gave `std::expected` four monadic members. `and_then(f)` runs `f` on the value and **returns what `f` returns**, so `f` must itself return a `std::expected` whose `error_type` is the same `E`; on an error the chain passes the error through untouched. `transform(f)` runs `f` on the value and wraps a plain result into `expected<U, E>`. `or_else(f)` runs only on the error path: `f(error)` must return an `expected` with the same `value_type`, which is how you recover, for example by substituting a default port when the key is missing. `transform_error(f)` maps `E` to a new error type `G`, typically at a layer boundary. So `get(cfg, "port").and_then(to_int).and_then(check_port)` reads top to bottom with no `if` between steps. C++23 also gave `std::optional` `and_then`, `transform` and `or_else`.
code
cpp · 38 lines#include <expected>
#include <iostream>
#include <map>
#include <string>
enum class ConfigError { missing_key, not_a_number, out_of_range };
using Config = std::map<std::string, std::string>;
std::expected<std::string, ConfigError> get(const Config& c, const std::string& k) {
if (auto it = c.find(k); it != c.end()) return it->second;
return std::unexpected(ConfigError::missing_key);
}
std::expected<int, ConfigError> to_int(const std::string& s) {
try { return std::stoi(s); } catch (...) { return std::unexpected(ConfigError::not_a_number); }
}
std::expected<int, ConfigError> check_port(int p) {
if (p < 1 || p > 65535) return std::unexpected(ConfigError::out_of_range);
return p;
}
int main() {
const Config cfg{{"port", "70000"}, {"workers", "4"}};
auto port = get(cfg, "port")
.and_then(to_int)
.and_then(check_port)
.or_else([](ConfigError e) -> std::expected<int, ConfigError> {
if (e == ConfigError::missing_key) return 8080;
return std::unexpected(e);
});
std::cout << port.has_value() << ' ' << static_cast<int>(port.error()) << '\n';
auto doubled = get(cfg, "workers").and_then(to_int).transform([](int n) { return n * 2; });
std::cout << *doubled << '\n';
auto msg = get(cfg, "timeout").transform_error([](ConfigError) { return std::string("timeout missing"); });
std::cout << msg.error() << '\n';
}go deeper
Recognise the four names and that they exist since C++23: and_then and transform work on the value, or_else and transform_error on the error.
Explain the return-type rule for each callable, why and_then needs the same error type, and how optional's or_else differs by taking no arguments.
Design chains that compile and stay readable: a shared error type per module, transform_error at layer boundaries, explicit lambda return types, and early returns where steps need several earlier results.
Decide whether a codebase adopts chains as house style, weighing readability and debugging cost against the boilerplate they remove, and what error type convention makes them composable.
## Why chaining exists Without help, every step of a fallible pipeline repeats the same three lines: call, test `has_value()`, return the error. C++23 added **monadic operations** to `std::expected` (and to `std::optional`) so a pipeline can be written as a chain where the error path is implicit. The general idea of monads belongs to functional programming material; what matters here is the exact contract of each C++ member. ## The four members | Member | Runs on | Callable receives | Callable must return | Result | |---|---|---|---|---| | `and_then(f)` | value | the value | `expected<U, E>` with the **same** `E` | what `f` returned, or the error copied through | | `transform(f)` | value | the value | any valid value type `U` (or `void`) | `expected<U, E>` | | `or_else(f)` | error | the error | `expected<T, G>` with the **same** `T` | the value copied through, or what `f` returned | | `transform_error(f)` | error | the error | any valid error type `G` | `expected<T, G>` | The draft states the type rules as **Mandates**, so breaking them is a compile error, not a runtime one. For `and_then`, `U` must be a specialization of `expected` and `is_same_v<typename U::error_type, E>` must be `true`. For `or_else`, `G::value_type` must be `T`. ## Reading a chain For a config loader whose steps are `get(cfg, key) -> expected<std::string, ConfigError>`, `to_int(std::string) -> expected<int, ConfigError>` and `check_port(int) -> expected<int, ConfigError>`: 1. `get(cfg, "port")` either holds the text or `missing_key`. 2. `.and_then(to_int)` runs only if the text is there; a parse failure becomes `not_a_number`. 3. `.and_then(check_port)` runs only on a parsed number; out-of-range becomes `out_of_range`. 4. `.or_else(recover)` runs only on an error; it can turn `missing_key` into a default of 8080 and pass every other error on with `return std::unexpected(e);`. Once any step fails, the following `and_then` and `transform` calls do not run their callables; the error travels to the end, or to the first `or_else` or `transform_error`. ## The classic compile errors - **Mismatched error types.** If `read` returns `expected<std::string, IoError>` and `parse` returns `expected<int, ParseError>`, `read().and_then(parse)` does not compile. libc++ reports `The result of f(std::move(value())) must have the same error_type as this expected`. The fix is a `transform_error` before the `and_then` that maps `IoError` into a common error type, or one shared error enum for the module. - **Returning a plain value from `and_then`'s callable.** `and_then` requires an `expected`; use `transform` when the step cannot fail. - **Returning `expected` from `transform`'s callable.** That compiles but nests: `expected<expected<int, E>, E>`. Use `and_then`. - **An `or_else` lambda with a deduced return type** that returns `8080` on one path and `std::unexpected(e)` on another fails to deduce one type; give it an explicit `-> std::expected<int, ConfigError>`. ## The optional versions `std::optional` gained `and_then`, `transform` and `or_else` in C++23 too. Its `and_then` callable must return an `optional`, its `transform` wraps a plain result, and its `or_else` takes **no arguments** (there is no error to pass) and must return an `optional` of the same type. Under `-std=c++20`, clang rejects `opt.transform(...)` with `no member named 'transform' in 'std::optional<int>'`. The same shape works on `std::optional` (C++23): ```cpp int workers = find("workers") // std::optional<std::string> .and_then(to_int) // to_int returns std::optional<int> .transform([](int n) { return n * 2; }) .or_else([] { return std::optional<int>(1); }) .value(); ``` With `{"workers", "4"}` in the config map, this compiled under `-std=c++23` and printed 8; a missing or unparsable entry yields 1. ## When a chain hurts Long chains of lambdas can be harder to debug than plain `if` statements, a breakpoint lands inside a library template, and captures by reference into a lambda stored for later can dangle. A senior answer uses chains for linear pipelines with one error type and falls back to early returns when steps need several earlier results at once.
- How do you chain a step returning expected<int, ParseError> after one returning expected<std::string, IoError>?Make the error types agree before the `and_then`: call `transform_error` on the first result to map `IoError` into a common type, for example a `ConfigError` enum or a variant of both, and make the parser return that type too. `and_then` mandates the same `error_type`, so without the mapping the chain does not compile.
- Does a failed step stop later and_then callables from running?Yes. On the error path `and_then` and `transform` do not invoke their callables; they construct the result from the existing error (`U(unexpect, error())`). The error reaches the end unchanged unless an `or_else` or `transform_error` handles or maps it on the way.
- and_then and transform are interchangeable; both just apply a function
- and_then automatically converts between different error types
- or_else runs on the value path to provide a fallback value
- A failed step still invokes the later callables with a default value
- std::optional has no monadic operations, only std::expected does
Assumes C++23, which added and_then, transform, or_else and transform_error to std::expected and and_then, transform and or_else to std::optional.