BioCMAMC-ST
results.hpp
1#ifndef __COMMON_RESULTS_HPP__
2#define __COMMON_RESULTS_HPP__
3#include <stdexcept>
4#include <utility>
5#include <variant>
6
7struct Success
8{
9};
10// TODO WIP
11template <typename S, typename T> struct Result : protected std::variant<S, T>
12{
13 explicit constexpr Result() noexcept : std::variant<S, T>{ S{} } {};
14 constexpr explicit Result(T const&& t) noexcept : std::variant<S, T>{ t }
15 {
16 }
17
18 constexpr explicit Result(S&& s) noexcept : std::variant<S, T>{ std::move(s) }
19 {
20 }
21
22 constexpr explicit
23 operator bool() const noexcept
24 {
25 return valid();
26 }
27
28 [[nodiscard]] constexpr bool
29 valid() const noexcept
30 {
31 return std::holds_alternative<S>(*this);
32 }
33 [[nodiscard]] constexpr bool
34 invalid() const noexcept
35 {
36 return !valid();
37 }
38
39 [[nodiscard]] constexpr auto
40 get() const noexcept -> T
41 {
42 return (invalid() ? std::get<T>(*this) : T());
43 }
44
45 [[nodiscard]] auto
46 gets() -> S
47 {
48 if (!invalid())
49 {
50 return std::move(std::get<S>(*this));
51 }
52 throw std::runtime_error("Deref None");
53 }
54
55 // template <typename Func, typename Err> auto match_const(Func&& f, Err&& r)
56 // const noexcept
57 // {
58 // if (this->valid())
59 // {
60 // return f(std::get<S>(*this));
61 // }
62 // else
63 // {
64 // return r(std::get<T>(*this));
65 // }
66 // }
67 //
68
69 template <typename Func, typename Err>
70 auto
71 match(Func&& f, Err&& r) noexcept
72 {
73 if (this->valid())
74 {
75 return f(std::forward<S>(std::get<S>(*this)));
76 }
77
78 return r(std::forward<T>(std::get<T>(*this)));
79 }
80};
81
82#endif
constexpr bool valid() const noexcept
Definition results.hpp:29
constexpr Result(S &&s) noexcept
Definition results.hpp:18
constexpr auto get() const noexcept -> T
Definition results.hpp:40
constexpr Result(T const &&t) noexcept
Definition results.hpp:14
auto gets() -> S
Definition results.hpp:46
auto match(Func &&f, Err &&r) noexcept
Definition results.hpp:71
constexpr bool invalid() const noexcept
Definition results.hpp:34
constexpr Result() noexcept
Definition results.hpp:13
Definition results.hpp:8