| 1 | // { dg-do compile { target c++17 } } |
| 2 | |
| 3 | // LWG 3886. Monad mo' problems |
| 4 | |
| 5 | #include <optional> |
| 6 | |
| 7 | void |
| 8 | test_cons() |
| 9 | { |
| 10 | struct MoveOnly { |
| 11 | MoveOnly(int, int) { } |
| 12 | MoveOnly(MoveOnly&&) { } |
| 13 | }; |
| 14 | |
| 15 | // The {0,0} should be deduced as MoveOnly not const MoveOnly |
| 16 | [[maybe_unused]] std::optional<const MoveOnly> o({0,0}); |
| 17 | } |
| 18 | |
| 19 | struct Tracker { |
| 20 | bool moved = false; |
| 21 | constexpr Tracker(int, int) { } |
| 22 | constexpr Tracker(const Tracker&) { } |
| 23 | constexpr Tracker(Tracker&&) : moved(true) { } |
| 24 | |
| 25 | // The follow means that is_assignable<const Tracker&, U> is true: |
| 26 | template<typename T> constexpr void operator=(T&&) const { } |
| 27 | }; |
| 28 | |
| 29 | #if __cpp_lib_optional >= 202106L // for constexpr assignment |
| 30 | void |
| 31 | test_assignment() |
| 32 | { |
| 33 | constexpr bool moved = [] { |
| 34 | std::optional<const Tracker> o; |
| 35 | // The {0,0} should be deduced as Tracker not const Tracker: |
| 36 | o = {0,0}; |
| 37 | // So the contained value should have been move constructed not copied: |
| 38 | return o->moved; |
| 39 | }(); |
| 40 | static_assert( moved ); |
| 41 | } |
| 42 | #endif |
| 43 | |
| 44 | void |
| 45 | test_value_or() |
| 46 | { |
| 47 | constexpr bool moved = [] { |
| 48 | std::optional<const Tracker> o; |
| 49 | return o.value_or({0,0}).moved; |
| 50 | }(); |
| 51 | static_assert( moved ); |
| 52 | |
| 53 | constexpr bool moved_rval = [] { |
| 54 | std::optional<const Tracker> o; |
| 55 | return std::move(o).value_or({0,0}).moved; |
| 56 | }(); |
| 57 | static_assert( moved_rval ); |
| 58 | } |