Template Class Expected#

Class Documentation#

template<typename T>
class Expected#

Expected<T> provides exception-free error handling for FFI functions.

Expected<T> is similar to Rust’s Result<T, Error> or C++23’s std::expected. It can hold either a success value of type T or an error of type Error.

Usage:

Expected<int> divide(int a, int b) {
  if (b == 0) {
    return Error("ValueError", "Division by zero");
  }
  return a / b;
}

Expected<int> result = divide(10, 2);
if (result.is_ok()) {
  int value = result.value();
} else {
  Error err = result.error();
}

Template Parameters:

T – The success type. Must be Any-compatible and cannot be Error.

Public Functions

inline Expected(T value)#

Implicit constructor from a success value.

Parameters:

value – The success value.

inline Expected(Error error)#

Implicit constructor from an error.

Parameters:

error – The error value.

template<typename E, typename = std::enable_if_t<std::is_base_of_v<Error, std::remove_cv_t<E>>>>
inline Expected(Unexpected<E> unexpected)#

Implicit constructor from an Unexpected wrapper.

inline bool is_ok() const#

Check if the Expected contains a success value.

Note

Checks for Error first to handle cases where T is a base class of Error.

Returns:

True if contains success value, false if contains error.

inline bool is_err() const#

Check if the Expected contains an error.

Returns:

True if contains error, false if contains success value.

inline bool has_value() const#

Alias for is_ok().

Returns:

True if contains success value.

inline T value() const &#

Access the success value. Throws the contained error if is_err().

inline T value() &&#

Access the success value (rvalue). Throws the contained error if is_err().

inline Error error() const &#

Access the error. Throws RuntimeError if is_ok().

inline Error error() &&#

Access the error (rvalue). Throws RuntimeError if is_ok().

template<typename U = std::remove_cv_t<T>>
inline T value_or(U &&default_value) const#

Get the success value or a default value.

Parameters:

default_value – The value to return if Expected contains an error.

Returns:

The success value if present, otherwise the default value.