[libc][NFC] Move aligned access implementations to separate header
[llvm-project.git] / libc / src / __support / CPP / expected.h
blob2fdcc5246d47318e3df56a306f82802dc4f0a360
1 //===-- Holds an expected or unexpected value -------------------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_LIBC_SUPPORT_CPP_EXPECTED_H
10 #define LLVM_LIBC_SUPPORT_CPP_EXPECTED_H
12 namespace __llvm_libc::cpp {
14 // This is used to hold an unexpected value so that a different constructor is
15 // selected.
16 template <class T> class unexpected {
17 T value;
19 public:
20 constexpr explicit unexpected(T value) : value(value) {}
21 constexpr T error() { return value; }
24 template <class T, class E> class expected {
25 union {
26 T exp;
27 E unexp;
29 bool is_expected;
31 public:
32 constexpr expected(T exp) : exp(exp), is_expected(true) {}
33 constexpr expected(unexpected<E> unexp)
34 : unexp(unexp.error()), is_expected(false) {}
36 constexpr bool has_value() { return is_expected; }
38 constexpr T value() { return exp; }
39 constexpr E error() { return unexp; }
41 constexpr operator bool() { return is_expected; }
43 constexpr T &operator*() { return exp; }
44 constexpr const T &operator*() const { return exp; }
45 constexpr T *operator->() { return &exp; }
46 constexpr const T *operator->() const { return &exp; }
49 } // namespace __llvm_libc::cpp
51 #endif // LLVM_LIBC_SUPPORT_CPP_EXPECTED_H