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 const E& error() const & noexcept;
12// constexpr E& error() & noexcept;
13// constexpr E&& error() && noexcept;
14// constexpr const E&& error() const && noexcept;
15
16#include <cassert>
17#include <concepts>
18#include <expected>
19#include <type_traits>
20#include <utility>
21
22#include "test_macros.h"
23
24// Test noexcept
25template <class T>
26concept ErrorNoexcept =
27 requires(T t) {
28 { std::forward<T>(t).error() } noexcept;
29 };
30
31static_assert(!ErrorNoexcept<int>);
32
33static_assert(ErrorNoexcept<std::expected<int, int>&>);
34static_assert(ErrorNoexcept<const std::expected<int, int>&>);
35static_assert(ErrorNoexcept<std::expected<int, int>&&>);
36static_assert(ErrorNoexcept<const std::expected<int, int>&&>);
37
38constexpr bool test() {
39 // non-const &
40 {
41 std::expected<int, int> e(std::unexpect, 5);
42 decltype(auto) x = e.error();
43 static_assert(std::same_as<decltype(x), int&>);
44 assert(x == 5);
45 }
46
47 // const &
48 {
49 const std::expected<int, int> e(std::unexpect, 5);
50 decltype(auto) x = e.error();
51 static_assert(std::same_as<decltype(x), const int&>);
52 assert(x == 5);
53 }
54
55 // non-const &&
56 {
57 std::expected<int, int> e(std::unexpect, 5);
58 decltype(auto) x = std::move(e).error();
59 static_assert(std::same_as<decltype(x), int&&>);
60 assert(x == 5);
61 }
62
63 // const &&
64 {
65 const std::expected<int, int> e(std::unexpect, 5);
66 decltype(auto) x = std::move(e).error();
67 static_assert(std::same_as<decltype(x), const int&&>);
68 assert(x == 5);
69 }
70
71 return true;
72}
73
74int main(int, char**) {
75 test();
76 static_assert(test());
77 return 0;
78}
79

source code of libcxx/test/std/utilities/expected/expected.expected/observers/error.pass.cpp