| 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 | |
| 11 | // |
| 12 | // constexpr expected(); |
| 13 | |
| 14 | // Constraints: is_default_constructible_v<T> is true. |
| 15 | // |
| 16 | // Effects: Value-initializes val. |
| 17 | // Postconditions: has_value() is true. |
| 18 | // |
| 19 | // Throws: Any exception thrown by the initialization of val. |
| 20 | |
| 21 | #include <cassert> |
| 22 | #include <expected> |
| 23 | #include <type_traits> |
| 24 | |
| 25 | #include "test_macros.h" |
| 26 | #include "../../types.h" |
| 27 | |
| 28 | struct NoDedefaultCtor { |
| 29 | NoDedefaultCtor() = delete; |
| 30 | }; |
| 31 | |
| 32 | // Test constraints |
| 33 | static_assert(std::is_default_constructible_v<std::expected<int, int>>); |
| 34 | static_assert(!std::is_default_constructible_v<std::expected<NoDedefaultCtor, int>>); |
| 35 | |
| 36 | struct MyInt { |
| 37 | int i; |
| 38 | friend constexpr bool operator==(const MyInt&, const MyInt&) = default; |
| 39 | }; |
| 40 | |
| 41 | template <class T, class E> |
| 42 | constexpr void testDefaultCtor() { |
| 43 | std::expected<T, E> e; |
| 44 | assert(e.has_value()); |
| 45 | assert(e.value() == T()); |
| 46 | } |
| 47 | |
| 48 | template <class T> |
| 49 | constexpr void testTypes() { |
| 50 | testDefaultCtor<T, bool>(); |
| 51 | testDefaultCtor<T, int>(); |
| 52 | testDefaultCtor<T, NoDedefaultCtor>(); |
| 53 | } |
| 54 | |
| 55 | constexpr bool test() { |
| 56 | testTypes<int>(); |
| 57 | testTypes<MyInt>(); |
| 58 | testTypes<TailClobberer<0>>(); |
| 59 | return true; |
| 60 | } |
| 61 | |
| 62 | void testException() { |
| 63 | #ifndef TEST_HAS_NO_EXCEPTIONS |
| 64 | struct Throwing { |
| 65 | Throwing() { throw Except{}; }; |
| 66 | }; |
| 67 | |
| 68 | try { |
| 69 | std::expected<Throwing, int> u; |
| 70 | assert(false); |
| 71 | } catch (Except) { |
| 72 | } |
| 73 | #endif // TEST_HAS_NO_EXCEPTIONS |
| 74 | } |
| 75 | |
| 76 | int main(int, char**) { |
| 77 | test(); |
| 78 | static_assert(test()); |
| 79 | testException(); |
| 80 | return 0; |
| 81 | } |
| 82 | |