Itasca C++ Interface
Loading...
Searching...
No Matches
expected.h
1#pragma once
2// This class is a temporary version of std::expected, to be used
3// until C++23 support is available.
4
5#include <variant>
6
7template <class E>
8class unexpected {
9public:
10 constexpr unexpected(const unexpected<E> &) = default;
11 constexpr unexpected(unexpected<E> &&) = default;
12 constexpr const E &error() const & noexcept { return e_; }
13 constexpr const E &error() & noexcept { return e_; }
14 constexpr const E &&error() const && noexcept { return e_; }
15 constexpr E &&error() const && noexcept { return e_; }
16 template <class E2>
17 friend constexpr bool operator==(const unexpected<E> &x,const unexpected<E2> &y) { return x.error()==y.error(); }
18private:
19 E e_;
20};
21
22struct unexpect_t {};
23
24template <class T,class E>
25class expected {
26public:
27 using value_type = T;
28 using error_type = E;
29 using unexpected_type = std::unexpected<E>;
30 constexpr expected() = default;
31 constexpr expected(const expected<T,E> &other) = default;
32 constexpr expected(expected<T,E> &&other) = default;
33 template <class U=T>
34 constexpr expected(const U &v) : v_(v) { }
35 template <class U=T>
36 constexpr expected(U &&v) : v_(std::move(v)) { }
37 template <class U=E>
38 constexpr explicit expected(const unexpected<U> &e) : v_(e.error()) { }
39 template <class U=E>
40 constexpr explicit expected(unexpected<U> &&e) : v_(std::move(e.error())) { }
41 template <class ... Args>
42 constexpr explicit expected(unexpect_t,Args &&...args) : v_(std::in_place_t<E>,args...) { }
43
44 constexpr const T *operator->() const { return &std::get<0>(v_); }
45 constexpr T *operator->() { return &std::get<0>(v_); }
46 constexpr const T &operator*() const { return std::get<0>(v_); }
47 constexpr T &operator*() { return std::get<0>(v_); }
48 constexpr bool has_value() const { return v_.index()==0; }
49 constexpr operator bool() const { return has_value(); }
50 constexpr const T &value() const { return std::get<0>(v_); }
51 constexpr T && value() { return std::get<0>(v_); }
52 constexpr const E &error() const { return std::get<1>(v_); }
53 constexpr E && error() { return std::get<1>(v_); }
54 constexpr T value_or(T &&default_value) const { return has_value() ? value() : default_value; }
55
56 template <class F>
57 constexpr auto and_then(F &&f) { if (has_value()) return std::invoke(std::forward<F>(f),**this); else return *this; }
58
59 template <class F>
60 constexpr auto or_else(F &&f) { if (has_value()) return *this; else return std::invoke(std::forward<F>(f),error()); }
61
62private:
63 std::variant<T,E> v_;
64};
65
66// EoF
Definition expected.h:25
Definition expected.h:8
Definition expected.h:22