summaryrefslogtreecommitdiff
path: root/asl
diff options
context:
space:
mode:
authorSteven Le Rouzic <steven.lerouzic@gmail.com>2024-11-02 18:25:11 +0100
committerSteven Le Rouzic <steven.lerouzic@gmail.com>2024-12-20 15:35:58 +0100
commitafd8e711ab35e8d21bc9c8397f31dcf7ecdec2e3 (patch)
treed7a22e7fafb12dde1957fd2fe1c550359ce69b21 /asl
parent343d872be9f91e5fcb9167021790831458cbf19c (diff)
Add value_or on option
Diffstat (limited to 'asl')
-rw-r--r--asl/option.hpp14
-rw-r--r--asl/tests/option_tests.cpp9
2 files changed, 23 insertions, 0 deletions
diff --git a/asl/option.hpp b/asl/option.hpp
index 2651a00..bb266ab 100644
--- a/asl/option.hpp
+++ b/asl/option.hpp
@@ -373,6 +373,20 @@ public:
return m_payload.as_init_unsafe();
}
}
+
+ template<typename U>
+ constexpr T value_or(U&& other_value) const&
+ requires copy_constructible<T> && convertible<U&&, T>
+ {
+ return has_value() ? value() : static_cast<T>(ASL_FWD(other_value));
+ }
+
+ template<typename U>
+ constexpr T value_or(U&& other_value) &&
+ requires move_constructible<T> && convertible<U&&, T>
+ {
+ return has_value() ? ASL_MOVE(value()) : static_cast<T>(ASL_FWD(other_value));
+ }
};
template<typename T>
diff --git a/asl/tests/option_tests.cpp b/asl/tests/option_tests.cpp
index dea046e..ec6e957 100644
--- a/asl/tests/option_tests.cpp
+++ b/asl/tests/option_tests.cpp
@@ -189,3 +189,12 @@ ASL_TEST(convert_move)
ASL_TEST_EXPECT(opt16.has_value());
ASL_TEST_EXPECT(opt16.value() == 10);
}
+
+ASL_TEST(value_or)
+{
+ asl::option<int> a = asl::nullopt;
+ asl::option<int> b = 2;
+
+ ASL_TEST_EXPECT(a.value_or(5) == 5);
+ ASL_TEST_EXPECT(b.value_or(5) == 2);
+}