61 lines · c
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-exception6//7//===----------------------------------------------------------------------===//8 9#ifndef LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H10#define LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H11 12#include "src/__support/macros/attributes.h"13#include "src/__support/macros/config.h"14 15namespace LIBC_NAMESPACE_DECL {16namespace cpp {17 18// This is used to hold an unexpected value so that a different constructor is19// selected.20template <class T> class unexpected {21 T value;22 23public:24 LIBC_INLINE constexpr explicit unexpected(T value) : value(value) {}25 LIBC_INLINE constexpr T error() { return value; }26};27 28template <class T> explicit unexpected(T) -> unexpected<T>;29 30template <class T, class E> class expected {31 union {32 T exp;33 E unexp;34 };35 bool is_expected;36 37public: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) {}41 42 LIBC_INLINE constexpr bool has_value() const { return is_expected; }43 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; }48 49 LIBC_INLINE constexpr operator bool() const { return is_expected; }50 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; }55};56 57} // namespace cpp58} // namespace LIBC_NAMESPACE_DECL59 60#endif // LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H61