The Problem We're Actually Solving
Let's start before the code. Imagine you write a function that divides two numbers. Easy, right? Except... what happens if someone tries to divide by zero? Your function needs a way to say "hey, something went wrong here" without crashing the whole program or lying about the result.
For decades, C++ programmers have had a few messy options:
- Throw an exception — works, but exceptions are expensive, and some codebases (game engines, embedded systems) avoid them entirely.
- Return an error code — cheap, but easy to ignore. Nobody checks return codes reliably, and you lose the "why" behind the failure.
- Use an output parameter — pass a pointer or reference to fill in with an error. Clunky and easy to mess up.
- Return a
std::optional— tells you something failed, but not what or why.
C++23 gives us a much cleaner tool: std::expected. Think of it as a box that either contains your successful result, or contains the reason it failed. Never both. Never neither.
The Simplest Way to Think About It
Picture a vending machine. You put in your money and press a button. Two things can happen:
- It works: you get your snack. 🍫
- It fails: it doesn't just give you nothing — it tells you why ("out of stock", "insert more coins", etc).
std::expected<T, E> is that vending machine in code form:
T= the type of the "snack" (your successful value)E= the type of the "reason it failed" (your error)
That's genuinely the whole concept. Everything else is just syntax.
Setting It Up
You need a C++23-compliant compiler (GCC 12+, Clang 16+, or MSVC with /std:c++latest, roughly speaking — always check your compiler's actual support table since this is a newer feature).
#include <expected>
#include <iostream>
#include <string>
Example 1: The Classic Divide-by-Zero
Let's build that division function.
#include <expected>
#include <iostream>
#include <string>
// This function either returns a double (success)
// or a string explaining what went wrong (failure)
std::expected<double, std::string> divide(double a, double b) {
if (b == 0.0) {
return std::unexpected("Cannot divide by zero, buddy.");
}
return a / b; // this becomes the "success" value automatically
}
int main() {
auto result = divide(10.0, 2.0);
if (result.has_value()) {
std::cout << "Success! Result: " << result.value() << "\n";
} else {
std::cout << "Oops! Error: " << result.error() << "\n";
}
auto badResult = divide(10.0, 0.0);
if (badResult) { // has_value() has a shorthand: just use it like a bool
std::cout << "Success! Result: " << badResult.value() << "\n";
} else {
std::cout << "Oops! Error: " << badResult.error() << "\n";
}
}
Output:
Success! Result: 5
Oops! Error: Cannot divide by zero, buddy.
Let's slow down and translate that code into English
std::expected<double, std::string>— "this function will either give you back adouble, or astd::stringexplaining the problem."return std::unexpected("...")— this is how you say "nope, it failed, here's why." You must wrap your error instd::unexpected(...)— it's the tag that tellsstd::expected"this is the failure branch, not the success branch."return a / b;— no wrapping needed here. If it's a valid value of typeT,std::expectedfigures out it's the success case automatically.result.has_value()— asks the box "did it work?"if (result)— literally the same thing ashas_value(), just shorter.std::expectedcan be used directly as a boolean condition.result.value()— "give me what's inside, assuming it worked."result.error()— "give me the failure reason, assuming it didn't work."
That's genuinely 90% of what you need to know.
Example 2: Chaining Operations (Where std::expected Really Shines)
Here's where things get fun. Imagine you're parsing user input, then converting it, then doing math on it — and any step could fail. Instead of nesting a pile of if-statements, std::expected lets you chain operations, kind of like std::optional does with and_then.
#include <expected>
#include <iostream>
#include <string>
#include <charconv>
// Step 1: try to convert a string to an integer
std::expected<int, std::string> parseNumber(const std::string& text) {
int value{};
auto result = std::from_chars(text.data(), text.data() + text.size(), value);
if (result.ec == std::errc()) {
return value;
}
return std::unexpected("'" + text + "' is not a valid number.");
}
// Step 2: make sure the number is positive
std::expected<int, std::string> requirePositive(int value) {
if (value <= 0) {
return std::unexpected("Number must be positive.");
}
return value;
}
// Step 3: square it
std::expected<int, std::string> square(int value) {
return value * value;
}
int main() {
std::string input = "6";
auto finalResult = parseNumber(input)
.and_then(requirePositive)
.and_then(square);
if (finalResult) {
std::cout << "Final result: " << *finalResult << "\n";
} else {
std::cout << "Something broke: " << finalResult.error() << "\n";
}
}
Output:
Final result: 36
What just happened here (plain English version)
Think of .and_then(...) like a relay race. Each runner (function) only runs if the previous runner successfully passed the baton. The moment someone drops the baton (returns an error), the whole race stops immediately, and that error gets carried straight to the finish line — no need to manually check "did it fail? did it fail? did it fail?" after every single step.
If you change input to "-5", the chain stops after requirePositive and square never even runs. Try it — it's kind of satisfying to watch it short-circuit.
Also notice: *finalResult works too — the * (dereference) operator is a shortcut for .value(), same idea as std::optional.
Example 3: A Custom Error Type (Not Just Strings)
Strings are fine for small examples, but in real projects you usually want a proper error type — often an enum class — so callers can check what kind of error happened, not just read a message.
#include <expected>
#include <iostream>
enum class ParseError {
Empty,
NotANumber,
TooLarge
};
// Turning the enum into a readable message, for when we DO want to print something
std::string describe(ParseError err) {
switch (err) {
case ParseError::Empty: return "The input was empty.";
case ParseError::NotANumber: return "That's not a number.";
case ParseError::TooLarge: return "That number is too big.";
}
return "Unknown error.";
}
std::expected<int, ParseError> parseAge(const std::string& text) {
if (text.empty()) {
return std::unexpected(ParseError::Empty);
}
if (!std::all_of(text.begin(), text.end(), ::isdigit)) {
return std::unexpected(ParseError::NotANumber);
}
int age = std::stoi(text);
if (age > 150) {
return std::unexpected(ParseError::TooLarge);
}
return age;
}
int main() {
for (const auto& input : {"25", "", "abc", "999"}) {
auto result = parseAge(input);
if (result) {
std::cout << "Valid age: " << *result << "\n";
} else {
std::cout << "Invalid (" << input << "): " << describe(result.error()) << "\n";
}
}
}
Output:
Valid age: 25
Invalid (): The input was empty.
Invalid (abc): That's not a number.
Invalid (999): That number is too big.
Why is this better than a string? Because now, calling code can actually branch on the error type — like showing a different UI message for "empty" versus "too large" — instead of doing fragile string comparisons.
The Handy Extra Tools
std::expected comes with a small toolbox of convenience methods worth knowing:
| Method | What it does in plain terms |
|---|---|
.value_or(fallback) |
"Give me the value, or if it failed, just use this fallback instead." |
.and_then(func) |
"If it worked, pass the value into the next function." |
.or_else(func) |
"If it failed, let me handle/recover from the error." |
.transform(func) |
"If it worked, transform the value into something else." |
.transform_error(func) |
"If it failed, transform the error into something else." |
Quick taste of value_or:
auto result = divide(10.0, 0.0);
double safeValue = result.value_or(0.0); // no error handling needed, just a fallback
std::cout << safeValue << "\n"; // prints 0
Why Not Just Use Exceptions?
Good question — exceptions still have their place. But std::expected gives you a few things exceptions don't:
- It's visible in the function signature. You can see right there in the return type that this function might fail — no digging through documentation or
try/catchguessing games. - The compiler forces you to think about it. You can't accidentally use the value without at least acknowledging there's an error branch (well — you can ignore it, but it's much more obvious when you do).
- No stack unwinding cost. Exceptions have runtime overhead when thrown;
std::expectedis just a regular return value, so it's typically cheaper and more predictable — useful for performance-sensitive code like games or real-time systems. - Errors are just data. You can store them, log them, pass them around, and inspect them like any normal value.
The tradeoff: it does add a little verbosity, and for truly catastrophic, unrecoverable failures (like memory corruption), exceptions or aborting are usually still the better tool.
The One-Paragraph Summary
std::expected<T, E> is a box that holds either a successful value of type T, or an error of type E — never both. You build a success case just by returning a value normally, and a failure case by wrapping it in std::unexpected(...). You check which one you got with has_value() or by treating it like a boolean, unwrap the value with .value() or *, and grab the error with .error(). Chain multiple fallible steps together with .and_then() so the first failure short-circuits everything after it. It's basically a safer, more expressive return code — one that forces you to actually deal with failure instead of quietly ignoring it.