1 | //===----------------------------------------------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | // UNSUPPORTED: c++03, c++11, c++14, c++17, c++20 |
10 | // <optional> |
11 | |
12 | // template<class F> constexpr optional or_else(F&&) &&; |
13 | // template<class F> constexpr optional or_else(F&&) const&; |
14 | |
15 | #include "MoveOnly.h" |
16 | |
17 | #include <cassert> |
18 | #include <optional> |
19 | |
20 | struct NonMovable { |
21 | NonMovable() = default; |
22 | NonMovable(NonMovable&&) = delete; |
23 | }; |
24 | |
25 | template <class Opt, class F> |
26 | concept has_or_else = requires(Opt&& opt, F&& f) { |
27 | {std::forward<Opt>(opt).or_else(std::forward<F>(f))}; |
28 | }; |
29 | |
30 | template <class T> |
31 | std::optional<T> return_optional() {} |
32 | |
33 | static_assert(has_or_else<std::optional<int>&, decltype(return_optional<int>)>); |
34 | static_assert(has_or_else<std::optional<int>&&, decltype(return_optional<int>)>); |
35 | static_assert(!has_or_else<std::optional<MoveOnly>&, decltype(return_optional<MoveOnly>)>); |
36 | static_assert(has_or_else<std::optional<MoveOnly>&&, decltype(return_optional<MoveOnly>)>); |
37 | static_assert(!has_or_else<std::optional<NonMovable>&, decltype(return_optional<NonMovable>)>); |
38 | static_assert(!has_or_else<std::optional<NonMovable>&&, decltype(return_optional<NonMovable>)>); |
39 | |
40 | std::optional<int> take_int(int) { return 0; } |
41 | void take_int_return_void(int) {} |
42 | |
43 | static_assert(!has_or_else<std::optional<int>, decltype(take_int)>); |
44 | static_assert(!has_or_else<std::optional<int>, decltype(take_int_return_void)>); |
45 | static_assert(!has_or_else<std::optional<int>, int>); |
46 | |
47 | constexpr bool test() { |
48 | { |
49 | std::optional<int> opt; |
50 | assert(opt.or_else([] { return std::optional<int>{0}; }) == 0); |
51 | opt = 1; |
52 | opt.or_else([] { |
53 | assert(false); |
54 | return std::optional<int>{}; |
55 | }); |
56 | } |
57 | { |
58 | std::optional<MoveOnly> opt; |
59 | opt = std::move(opt).or_else([] { return std::optional<MoveOnly>{MoveOnly{}}; }); |
60 | std::move(opt).or_else([] { |
61 | assert(false); |
62 | return std::optional<MoveOnly>{}; |
63 | }); |
64 | } |
65 | |
66 | return true; |
67 | } |
68 | |
69 | int main(int, char**) { |
70 | test(); |
71 | static_assert(test()); |
72 | return 0; |
73 | } |
74 | |