[NFC][Py Reformat] Added more commits to .git-blame-ignore-revs
[llvm-project.git] / libc / src / __support / CPP / expected.h
blobaab80c2d983d68f6e4fc1ea9c3f6735fc33d1310
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 T() { return exp; }
42 constexpr operator bool() { return is_expected; }
44 constexpr T &operator*() { return exp; }
45 constexpr const T &operator*() const { return exp; }
46 constexpr T *operator->() { return &exp; }
47 constexpr const T *operator->() const { return &exp; }
50 } // namespace __llvm_libc::cpp
52 #endif // LLVM_LIBC_SUPPORT_CPP_EXPECTED_H