1 //===-- Holds an expected or unexpected value -------------------*- C++ -*-===//
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 #ifndef LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H
10 #define LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H
12 #include "src/__support/macros/attributes.h"
13 #include "src/__support/macros/config.h"
15 namespace LIBC_NAMESPACE_DECL
{
18 // This is used to hold an unexpected value so that a different constructor is
20 template <class T
> class unexpected
{
24 LIBC_INLINE
constexpr explicit unexpected(T value
) : value(value
) {}
25 LIBC_INLINE
constexpr T
error() { return value
; }
28 template <class T
> explicit unexpected(T
) -> unexpected
<T
>;
30 template <class T
, class E
> class expected
{
38 LIBC_INLINE
constexpr expected(T exp
) : exp(exp
), is_expected(true) {}
39 LIBC_INLINE
constexpr expected(unexpected
<E
> unexp
)
40 : unexp(unexp
.error()), is_expected(false) {}
42 LIBC_INLINE
constexpr bool has_value() const { return is_expected
; }
44 LIBC_INLINE
constexpr T
&value() { return exp
; }
45 LIBC_INLINE
constexpr E
&error() { return unexp
; }
46 LIBC_INLINE
constexpr const T
&value() const { return exp
; }
47 LIBC_INLINE
constexpr const E
&error() const { return unexp
; }
49 LIBC_INLINE
constexpr operator bool() const { return is_expected
; }
51 LIBC_INLINE
constexpr T
&operator*() { return exp
; }
52 LIBC_INLINE
constexpr const T
&operator*() const { return exp
; }
53 LIBC_INLINE
constexpr T
*operator->() { return &exp
; }
54 LIBC_INLINE
constexpr const T
*operator->() const { return &exp
; }
58 } // namespace LIBC_NAMESPACE_DECL
60 #endif // LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H