xref: /llvm-project/libcxx/test/std/utilities/expected/expected.unexpected/swap/swap.member.pass.cpp (revision 6a54dfbfe534276d644d7f9c027f0deeb748dd53)
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 // constexpr void swap(unexpected& other) noexcept(is_nothrow_swappable_v<E>);
12 //
13 // Mandates: is_swappable_v<E> is true.
14 //
15 // Effects: Equivalent to: using std::swap; swap(unex, other.unex);
16 
17 #include <cassert>
18 #include <concepts>
19 #include <expected>
20 #include <utility>
21 
22 // test noexcept
23 struct NoexceptSwap {
24   friend void swap(NoexceptSwap&, NoexceptSwap&) noexcept;
25 };
26 
27 struct MayThrowSwap {
28   friend void swap(MayThrowSwap&, MayThrowSwap&);
29 };
30 
31 template <class T>
32 concept MemberSwapNoexcept =
33     requires(T& t1, T& t2) {
34       { t1.swap(t2) } noexcept;
35     };
36 
37 static_assert(MemberSwapNoexcept<std::unexpected<NoexceptSwap>>);
38 static_assert(!MemberSwapNoexcept<std::unexpected<MayThrowSwap>>);
39 
40 struct ADLSwap {
41   constexpr ADLSwap(int ii) : i(ii) {}
42   ADLSwap& operator=(const ADLSwap&) = delete;
43   int i;
44   constexpr friend void swap(ADLSwap& x, ADLSwap& y) { std::swap(x.i, y.i); }
45 };
46 
47 constexpr bool test() {
48   // using std::swap;
49   {
50     std::unexpected<int> unex1(5);
51     std::unexpected<int> unex2(6);
52     unex1.swap(unex2);
53     assert(unex1.error() == 6);
54     assert(unex2.error() == 5);
55   }
56 
57   // adl swap
58   {
59     std::unexpected<ADLSwap> unex1(5);
60     std::unexpected<ADLSwap> unex2(6);
61     unex1.swap(unex2);
62     assert(unex1.error().i == 6);
63     assert(unex2.error().i == 5);
64   }
65   return true;
66 }
67 
68 int main(int, char**) {
69   test();
70   static_assert(test());
71   return 0;
72 }
73