Added getOr() and getOrThrow() utility functions to optional.

This commit is contained in:
Patrick Wuttke
2026-02-17 10:23:28 +01:00
parent 40840b0c7d
commit 5e09113f22

View File

@@ -156,6 +156,14 @@ public:
public:
[[nodiscard]] inline std::remove_reference_t<TValue>& get() noexcept;
[[nodiscard]] inline const std::remove_reference_t<TValue>& get() const noexcept;
template<typename TDefault>
[[nodiscard]] inline std::remove_reference_t<TValue> getOr(TDefault&& defaultValue) const& MIJIN_NOEXCEPT_IF((std::is_nothrow_constructible_v<TValue, TDefault&&> && std::is_nothrow_copy_constructible_v<TValue>));
template<typename TDefault>
[[nodiscard]] inline std::remove_reference_t<TValue> getOr(TDefault&& defaultValue) && MIJIN_NOEXCEPT_IF((std::is_nothrow_constructible_v<TValue, TDefault&&> && std::is_nothrow_move_constructible_v<TValue>));
template<typename TException, typename... TArgs>
[[nodiscard]] inline std::remove_reference_t<TValue> getOrThrow(TArgs&&... args) const&;
template<typename TException, typename... TArgs>
[[nodiscard]] inline std::remove_reference_t<TValue> 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<TValue>& Optional<TValue>::get() const noex
return storage_.get();
}
template<typename TValue>
template<typename TDefault>
std::remove_reference_t<TValue> Optional<TValue>::getOr(TDefault&& defaultValue) const& MIJIN_NOEXCEPT_IF((std::is_nothrow_constructible_v<TValue, TDefault&&> && std::is_nothrow_copy_constructible_v<TValue>))
{
if (!empty()) {
return get();
}
return TValue(std::forward<TDefault>(defaultValue));
}
template<typename TValue>
template<typename TDefault>
std::remove_reference_t<TValue> Optional<TValue>::getOr(TDefault&& defaultValue) && MIJIN_NOEXCEPT_IF((std::is_nothrow_constructible_v<TValue, TDefault&&> && std::is_nothrow_move_constructible_v<TValue>))
{
if (!empty()) {
return std::move(get());
}
return TValue(std::forward<TDefault>(defaultValue));
}
template<typename TValue>
template<typename TException, typename... TArgs>
std::remove_reference_t<TValue> Optional<TValue>::getOrThrow(TArgs&&... args) const&
{
if (!empty()) {
return get();
}
throw TException(std::forward<TArgs>(args)...);
}
template<typename TValue>
template<typename TException, typename... TArgs>
std::remove_reference_t<TValue> Optional<TValue>::getOrThrow(TArgs&&... args) &&
{
if (!empty()) {
return std::move(get());
}
throw TException(std::forward<TArgs>(args)...);
}
template<typename TValue>
inline void Optional<TValue>::reset() noexcept
{