std::expected<T, E> holds either a value of type T or an error of type E. An error is created with std::unexpected. It is available from the expected header:

#include <expected>

std::expected<int, std::string#include <string>> to_int(char c) {
  if (c >= '0' && c <= '9') {
    return c - '0';
  }
  return std::unexpected("Not a digit.");
}

Whether an expected has a value can be checked by converting it to a bool or with has_value():

auto r = to_int('2');
static_cast<bool>(r);  // true
r.has_value();         // true

If the expected has a value, it can be accessed with * or value():

auto r = to_int('4');
if (r) {
  *r;  // 4
}
r.value();  // 4

Warning

If there is an error, using * is undefined behaviour and value() will throw std::bad_expected_access#include <expected>.

If the expected has an error, it can be accessed with error():

auto r = to_int('x');
if (!r) {
  r.error();  // "Not a digit."
}

Warning

If there is a value, using error() is undefined behaviour.

value_or() returns the value, or a fallback when there's an error:

to_int('x').value_or(0);  // 0

transform() applies a function to the value if there is one:

to_int('7').transform([](int x) { return x * 2; });  // Holds 14.
to_int('x').transform([](int x) { return x * 2; });  // Holds "Not a digit.".

and_then() calls a function that returns another expected, if there is a value:

std::expected<int, std::string#include <string>> half(int x) {
  if (x % 2 != 0) {
    return std::unexpected("Odd.");
  }
  return x / 2;
}

to_int('8').and_then(half);  // Holds 4.
to_int('7').and_then(half);  // Holds "Odd.".
to_int('x').and_then(half);  // Holds "Not a digit.".

or_else() calls a function that returns another expected, if there is an error:

auto zero = [](const std::string#include <string>&) -> std::expected<int, std::string#include <string>> { return 0; };
to_int('7').or_else(zero);  // Holds 7.
to_int('x').or_else(zero);  // Holds 0.

Note

Prefer std::expected over exceptions for errors the caller is expected to handle, since the error is visibly part of the function signature. Exceptions suit rare errors that can't be handled near where they occur.

References