packio
expected.h
1 // This Source Code Form is subject to the terms of the Mozilla Public
2 // License, v. 2.0. If a copy of the MPL was not distributed with this
3 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4 
5 #ifndef PACKIO_EXPECTED_H
6 #define PACKIO_EXPECTED_H
7 
8 #include <variant>
9 
10 namespace packio {
11 namespace internal {
12 
13 template <typename Error>
14 struct unexpected {
15 public:
16  explicit unexpected(Error error) : error_(std::move(error)) {}
17  Error& error() { return error_; }
18 
19 private:
20  Error error_;
21 };
22 
23 template <typename T, typename Error>
24 class expected {
25 public:
26  template <typename G>
27  expected(unexpected<G> unexpected)
28  : data_(Error(std::move(unexpected.error())))
29  {
30  }
31  expected(T value) : data_(std::move(value)) {}
32 
33  Error& error() { return std::get<Error>(data_); }
34  T& value() { return std::get<T>(data_); }
35 
36  explicit operator bool() const { return std::holds_alternative<T>(data_); }
37  T& operator*() { return value(); }
38  T* operator->() { return &this->operator*(); }
39 
40 private:
41  std::variant<T, Error> data_;
42 };
43 
44 } // internal
45 } // packio
46 
47 #endif // PACKIO_EXPECTED_H
The packio namespace.
Definition: arg.h:14