Skip to content

Commit

Permalink
Add unwrap_or method to Result class
Browse files Browse the repository at this point in the history
  • Loading branch information
GregoryKogan committed Dec 26, 2023
1 parent 26d8263 commit 158b895
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/result.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ template <typename T, typename E> 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.
Expand Down Expand Up @@ -137,6 +138,17 @@ template <typename T, typename E> inline auto Result<T, E>::unwrap() const -> T
return std::get<ContentType::Value>(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 <typename T, typename E> inline auto Result<T, E>::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.
Expand Down
2 changes: 2 additions & 0 deletions tests/unwrap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ TEST(Unwrap, Ok) {
res::Result<int, std::string> 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);
}

Expand All @@ -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);
}

0 comments on commit 158b895

Please sign in to comment.