Files
Library/include/Void/Result/Result.hpp
T
2026-05-03 18:09:46 +03:00

65 lines
2.1 KiB
C++

#pragma once
#include <Void/Result/Error.hpp>
#include <concepts>
#include <expected>
#include <string>
#include <type_traits>
#include <utility>
namespace Void::Result
{
/// `Result<T, E>` is a thin alias over `std::expected<T, E>`.
///
/// std::expected already provides every monadic operation we need
/// (`and_then`, `or_else`, `transform` (= map), `transform_error`
/// (= map_err), `value_or`). The wrappers in this module add
/// context-chain support (see `with_context` below) and a default
/// error type (`Void::Result::Error`).
template <typename T, typename E = Error>
using Result = std::expected<T, E>;
/// Tag wrapper for failure construction. Shorthand for
/// `std::unexpected<E>`.
template <typename E = Error> using Failure = std::unexpected<E>;
/// Convenience factory for a successful Result.
template <typename T>
[[nodiscard]] constexpr Result<std::remove_cvref_t<T>> ok(T&& value)
{
return Result<std::remove_cvref_t<T>>{std::forward<T>(value)};
}
/// Convenience factory for a failed Result with the default Error type.
[[nodiscard]] inline Failure<Error> fail(std::string message)
{
return Failure<Error>{Error{std::move(message)}};
}
/// Convenience factory for a failed Result with an arbitrary E.
/// Constrained so string-like types resolve to the `std::string`
/// overload above (otherwise a literal `"..."` deduces E to a char
/// array).
template <typename E>
requires(!std::convertible_to<std::remove_cvref_t<E>, std::string>)
[[nodiscard]] constexpr Failure<std::remove_cvref_t<E>> fail(E&& error)
{
return Failure<std::remove_cvref_t<E>>{std::forward<E>(error)};
}
/// Add a context layer to a failed Result. On success, the result is
/// returned unchanged. Requires that `E` exposes a
/// `with_context(std::string) const&` method (the bundled `Error`
/// type does).
template <typename T, typename E>
[[nodiscard]] Result<T, E> with_context(Result<T, E> r, std::string ctx)
{
if (r) {
return r;
}
return Failure<E>{std::move(r).error().with_context(std::move(ctx))};
}
} // namespace Void::Result