Debian Codegraph @

libstdc++-v3/testsuite/20_util/optional/constexpr/assign.cc

raw
1 // { dg-do compile { target c++20 } }
2
3 #include <optional>
4 #include <testsuite_hooks.h>
5
6
7 constexpr bool
8 test_assign()
9 {
10 std::optional<int> oi(1);
11 std::optional<unsigned> ou(2u), ou3(3u);
12
13 // optional& operator=(nullopt_t);
14 oi = std::nullopt;
15 VERIFY( ! oi.has_value() );
16 oi = std::nullopt;
17 VERIFY( ! oi.has_value() );
18
19 struct S {
20 constexpr S() { }
21 constexpr S(char, int, unsigned) { }
22 };
23 std::optional<S> os1, os2;
24
25 // template<class U = T> optional& operator=(U&&);
26 os1 = {'0', 1, 2u};
27 VERIFY( os1.has_value() );
28 os2 = {'3', 4, 5u};
29 VERIFY( os2.has_value() );
30 oi = 0u;
31 VERIFY( *oi == 0 );
32 oi = 1u;
33 VERIFY( *oi == 1 );
34
35 // template<class U> optional& operator=(const optional<U>&);
36 oi = ou;
37 VERIFY( *oi == 2 );
38 oi = ou3;
39 VERIFY( *oi == 3 );
40
41 // template<class U> optional& operator=(optional<U>&&);
42 oi = std::move(ou);
43 VERIFY( *oi == 2 );
44 oi = std::move(ou);
45 VERIFY( *oi == 2 );
46 oi = std::move(ou3);
47 VERIFY( *oi == 3 );
48
49 return true;
50 }
51
52 static_assert( test_assign() );
53
54 constexpr bool
55 test_emplace()
56 {
57 struct S
58 {
59 constexpr S(int i) : val(i) { }
60 constexpr S(int i, int j) : val(i + j) { }
61 constexpr S(std::initializer_list<char> l, int i = 0) : val(i)
62 {
63 for (char c : l)
64 val -= c;
65 }
66
67 int val;
68
69 constexpr bool operator==(int i) const { return val == i; }
70 };
71
72
73 std::optional<S> os;
74
75 // template<class... Args> constexpr T& emplace(Args&&...);
76 os.emplace(1);
77 VERIFY( *os == 1 );
78 os.emplace(2);
79 VERIFY( *os == 2 );
80 os.emplace(2, 3);
81 VERIFY( *os == 5 );
82
83 // template<class U, class... Args>
84 // constexpr T& emplace(initializer_list<U>, Args&&...);
85 os.emplace({'3', '4', '5'});
86 VERIFY( *os == -156 );
87 os.emplace({'6', '7', '8'}, 25);
88 VERIFY( *os == -140 );
89
90 return true;
91 }
92
93 static_assert( test_emplace() );