result: implicit unwrap on conversion to result T
[staging/windowmanager.git] / src / result.hpp
1 //
2 // Created by mfritzsc on 7/12/17.
3 //
4
5 #ifndef TMCAGLWM_RESULT_HPP
6 #define TMCAGLWM_RESULT_HPP
7
8 #include <experimental/optional>
9
10 namespace wm {
11
12 using std::experimental::optional;
13 using std::experimental::nullopt;
14
15 // We only ever return a string as an error - so just parametrize
16 // this over result type T
17 template <typename T>
18 struct result {
19    char const *e;
20    optional<T> t;
21
22    bool is_ok() const { return this->t != nullopt; }
23    bool is_err() const { return this->e != nullptr; }
24
25    T unwrap() {
26       if (this->e != nullptr) {
27          throw std::logic_error(this->e);
28       }
29       return this->t.value();
30    }
31
32    operator T() {
33       return this->unwrap();
34    }
35
36    char const *unwrap_err() { return this->e; }
37 };
38
39 template <typename T>
40 struct result<T> Err(char const *e) {
41    return result<T>{e, nullopt};
42 }
43
44 template <typename T>
45 struct result<T> Ok(T t) {
46    return result<T>{nullptr, t};
47 }
48
49 }  // namespace wm
50
51 #endif  // TMCAGLWM_RESULT_HPP