Skip to content

Commit

Permalink
[OptionalReference] Add value_or() function
Browse files Browse the repository at this point in the history
  • Loading branch information
alexkaratarakis committed Sep 19, 2024
1 parent 89923df commit 1ad10a6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
10 changes: 10 additions & 0 deletions include/fixed_containers/optional_reference.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ class OptionalReference
return *val();
}

[[nodiscard]] constexpr reference value_or(reference default_value) const&
{
if (!has_value())
{
return default_value;
}

return *val();
}

constexpr explicit operator bool() const noexcept { return has_value(); }
[[nodiscard]] constexpr bool has_value() const noexcept { return val() != nullptr; }

Expand Down
23 changes: 23 additions & 0 deletions test/optional_reference_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,29 @@ TEST(OptionalReference, Value)
}
}

TEST(OptionalReference, ValueOr)
{
{
int fallback_value = 99;

using T = OptionalReference<int>;
const T val1{};
int& result = val1.value_or(fallback_value);
EXPECT_EQ(99, result);
result = 88;
EXPECT_EQ(88, result);
EXPECT_EQ(88, fallback_value);
}
{
const int fallback_value = 77;

constexpr int ENTRY_1 = 5;
const OptionalReference<const int> val1(ENTRY_1);
const int& result = val1.value_or(fallback_value);
EXPECT_EQ(5, result);
}
}

TEST(OptionalReference, DereferenceOperator)
{
{
Expand Down

0 comments on commit 1ad10a6

Please sign in to comment.