Add maybe_t::value_or

This enables getting the value or returning the passed-in value.
This is helpful for "default if none."
This commit is contained in:
ridiculousfish 2022-10-16 15:40:33 -07:00
parent 892a820672
commit fe7d095647
2 changed files with 17 additions and 0 deletions

View file

@ -6435,6 +6435,10 @@ void test_maybe() {
do_test(std::is_copy_assignable<maybe_t<noncopyable>>::value == false);
do_test(std::is_copy_constructible<maybe_t<noncopyable>>::value == false);
// We can construct a maybe_t from noncopyable things.
maybe_t<noncopyable> nmt{make_unique<int>(42)};
do_test(**nmt == 42);
maybe_t<std::string> c1{"abc"};
maybe_t<std::string> c2 = c1;
do_test(c1.value() == "abc");
@ -6442,6 +6446,11 @@ void test_maybe() {
c2 = c1;
do_test(c1.value() == "abc");
do_test(c2.value() == "abc");
do_test(c2.value_or("derp") == "abc");
do_test(c2.value_or("derp") == "abc");
c2.reset();
do_test(c2.value_or("derp") == "derp");
}
void test_layout_cache() {

View file

@ -209,6 +209,14 @@ class maybe_t : private maybe_detail::conditionally_copyable_t<T> {
// Transfer the value to the caller.
T acquire() { return impl_.acquire(); }
// Return (a copy of) our value, or the given value if we are empty.
T value_or(T v) const {
if (this->has_value()) {
return this->value();
}
return v;
}
// Clear the value.
void reset() { impl_.reset(); }