diff --git a/src/result.h b/src/result.h index f98cc55..1eeb468 100644 --- a/src/result.h +++ b/src/result.h @@ -39,6 +39,7 @@ template class Result { [[nodiscard]] auto is_err() const noexcept -> bool; [[nodiscard]] auto unwrap() const -> T; + [[nodiscard]] auto unwrap_or(const T &default_value) const noexcept -> T; [[nodiscard]] auto unwrap_err() const -> E; /// @brief `true` if the Result is successful, `false` otherwise. @@ -137,6 +138,17 @@ template inline auto Result::unwrap() const -> T return std::get(content_); } +/// @brief Returns the value of a successful Result or a default value if the Result is unsuccessful. +/// @tparam T +/// @tparam E +/// @param default_value +template inline auto Result::unwrap_or(const T &default_value) const noexcept -> T { + try { + if (is_ok()) { return unwrap(); } + } catch (const std::exception &e) { return default_value; } + return default_value; +} + /// @brief Returns the error of an unsuccessful Result. /// @return E /// @throw std::runtime_error if the Result is successful. diff --git a/tests/unwrap.cpp b/tests/unwrap.cpp index 5bea7f8..ce5fdc0 100644 --- a/tests/unwrap.cpp +++ b/tests/unwrap.cpp @@ -7,6 +7,7 @@ TEST(Unwrap, Ok) { res::Result result = res::Ok(value); EXPECT_EQ(result.unwrap(), value); + EXPECT_EQ(result.unwrap_or(0), value); EXPECT_THROW(auto res = result.unwrap_err(), std::runtime_error); } @@ -16,4 +17,5 @@ TEST(Unwrap, Err) { EXPECT_EQ(result.unwrap_err(), value); EXPECT_THROW(auto res = result.unwrap(), std::runtime_error); + EXPECT_EQ(result.unwrap_or(0), 0); } \ No newline at end of file