SpECTRE  v2026.11.11
Loading...
Searching...
No Matches
Expected< T, E > Class Template Reference

Holds either a value of type T or an error of type E, like a minimal version of C++23's std::expected. More...

#include <Expected.hpp>

Public Member Functions

constexpr Expected (T value)
constexpr Expected (Unexpected< E > unexpected)
constexpr bool has_value () const
constexpr operator bool () const
constexpr const E & error () const
 The error. It is an error to call this if has_value() is true.
constexpr const T & value () const &
 The value. It is an error to call this if has_value() is false.
constexpr T & value () &
 The value. It is an error to call this if has_value() is false.
constexpr T && value () &&
 The value. It is an error to call this if has_value() is false.

Detailed Description

template<typename T, typename E>
class Expected< T, E >

Holds either a value of type T or an error of type E, like a minimal version of C++23's std::expected.

Construct an Expected from a T to hold a value, or from an Unexpected<E> to hold an error. Return an Expected from functions that can fail to let the caller decide how to handle the failure.

Expected<double, SqrtError> checked_sqrt(const double x) {
if (x < 0.0) {
return Unexpected{SqrtError::Negative};
}
return Unexpected{SqrtError::Infinite};
}
return sqrt(x);
}
double sqrt_or_zero(const double x) {
const auto result = checked_sqrt(x);
if (not result.has_value()) {
return result.error() == SqrtError::Negative ? 0.0 : x;
}
return result.value();
}

Calling value() when there is an error, or error() when there is a value, is an error (also in release builds).

Unlike std::expected, this class stores both a T and an E, so both must be default-constructible and the one that isn't held is default-constructed. This keeps the class simple.


The documentation for this class was generated from the following file:
  • src/Utilities/Expected.hpp