1 //===----------------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
11 // constexpr expected(const expected& rhs);
13 // Effects: If rhs.has_value() is false, direct-non-list-initializes unex with rhs.error().
15 // Postconditions: rhs.has_value() == this->has_value().
17 // Throws: Any exception thrown by the initialization of unex.
20 // - This constructor is defined as deleted unless is_copy_constructible_v<E> is true.
21 // - This constructor is trivial if is_trivially_copy_constructible_v<E> is true.
25 #include <type_traits>
28 #include "test_macros.h"
29 #include "../../types.h"
32 NonCopyable(const NonCopyable
&) = delete;
35 struct CopyableNonTrivial
{
37 constexpr CopyableNonTrivial(int ii
) : i(ii
) {}
38 constexpr CopyableNonTrivial(const CopyableNonTrivial
& o
) { i
= o
.i
; }
39 friend constexpr bool operator==(const CopyableNonTrivial
&, const CopyableNonTrivial
&) = default;
42 // Test: This constructor is defined as deleted unless is_copy_constructible_v<E> is true.
43 static_assert(std::is_copy_constructible_v
<std::expected
<void, int>>);
44 static_assert(std::is_copy_constructible_v
<std::expected
<void, CopyableNonTrivial
>>);
45 static_assert(!std::is_copy_constructible_v
<std::expected
<void, NonCopyable
>>);
47 // Test: This constructor is trivial if is_trivially_copy_constructible_v<E> is true.
48 static_assert(std::is_trivially_copy_constructible_v
<std::expected
<void, int>>);
49 static_assert(!std::is_trivially_copy_constructible_v
<std::expected
<void, CopyableNonTrivial
>>);
51 constexpr bool test() {
52 // copy the error non-trivial
54 const std::expected
<void, CopyableNonTrivial
> e1(std::unexpect
, 5);
56 assert(!e2
.has_value());
57 assert(e2
.error().i
== 5);
60 // copy the error trivial
62 const std::expected
<void, int> e1(std::unexpect
, 5);
64 assert(!e2
.has_value());
65 assert(e2
.error() == 5);
68 // copy TailClobberer as error
70 const std::expected
<void, TailClobberer
<1>> e1(std::unexpect
);
72 assert(!e2
.has_value());
78 void testException() {
79 #ifndef TEST_HAS_NO_EXCEPTIONS
82 Throwing(const Throwing
&) { throw Except
{}; }
85 // throw on copying error
87 const std::expected
<void, Throwing
> e1(std::unexpect
);
89 [[maybe_unused
]] auto e2
= e1
;
95 #endif // TEST_HAS_NO_EXCEPTIONS
98 int main(int, char**) {
100 static_assert(test());