From 5e09113f22a31396f42a2ca31eb2bdc4777f15da Mon Sep 17 00:00:00 2001 From: Patrick Wuttke Date: Tue, 17 Feb 2026 10:23:28 +0100 Subject: [PATCH] Added getOr() and getOrThrow() utility functions to optional. --- source/mijin/container/optional.hpp | 48 +++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/source/mijin/container/optional.hpp b/source/mijin/container/optional.hpp index 80f1fac..6411773 100644 --- a/source/mijin/container/optional.hpp +++ b/source/mijin/container/optional.hpp @@ -156,6 +156,14 @@ public: public: [[nodiscard]] inline std::remove_reference_t& get() noexcept; [[nodiscard]] inline const std::remove_reference_t& get() const noexcept; + template + [[nodiscard]] inline std::remove_reference_t getOr(TDefault&& defaultValue) const& MIJIN_NOEXCEPT_IF((std::is_nothrow_constructible_v && std::is_nothrow_copy_constructible_v)); + template + [[nodiscard]] inline std::remove_reference_t getOr(TDefault&& defaultValue) && MIJIN_NOEXCEPT_IF((std::is_nothrow_constructible_v && std::is_nothrow_move_constructible_v)); + template + [[nodiscard]] inline std::remove_reference_t getOrThrow(TArgs&&... args) const&; + template + [[nodiscard]] inline std::remove_reference_t getOrThrow(TArgs&&... args) &&; [[nodiscard]] constexpr bool empty() const noexcept { return storage_.empty(); } inline void reset() noexcept; @@ -350,6 +358,46 @@ inline const std::remove_reference_t& Optional::get() const noex return storage_.get(); } +template +template +std::remove_reference_t Optional::getOr(TDefault&& defaultValue) const& MIJIN_NOEXCEPT_IF((std::is_nothrow_constructible_v && std::is_nothrow_copy_constructible_v)) +{ + if (!empty()) { + return get(); + } + return TValue(std::forward(defaultValue)); +} + +template +template +std::remove_reference_t Optional::getOr(TDefault&& defaultValue) && MIJIN_NOEXCEPT_IF((std::is_nothrow_constructible_v && std::is_nothrow_move_constructible_v)) +{ + if (!empty()) { + return std::move(get()); + } + return TValue(std::forward(defaultValue)); +} + +template +template +std::remove_reference_t Optional::getOrThrow(TArgs&&... args) const& +{ + if (!empty()) { + return get(); + } + throw TException(std::forward(args)...); +} + +template +template +std::remove_reference_t Optional::getOrThrow(TArgs&&... args) && +{ + if (!empty()) { + return std::move(get()); + } + throw TException(std::forward(args)...); +} + template inline void Optional::reset() noexcept {