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 operator bool() const noexcept
23 {
24 return valid();
25 }
26
27 [[nodiscard]] constexpr bool valid() const noexcept
28 {
29 return std::holds_alternative<S>(*this);
30 }
31 [[nodiscard]] constexpr bool invalid() const noexcept
32 {
33 return !valid();
34 }
35
36 [[nodiscard]] constexpr auto get() const noexcept -> T
37 {
38 return (invalid() ? std::get<T>(*this) : T());
39 }
40
41 [[nodiscard]] auto gets() const -> S
42 {
43 if (!invalid())
44 {
45 return std::move(std::get<S>(*this));
46 }
47 throw std::runtime_error("Deref None");
48 }
49
50 // template <typename Func, typename Err> auto match_const(Func&& f, Err&& r)
51 // const noexcept
52 // {
53 // if (this->valid())
54 // {
55 // return f(std::get<S>(*this));
56 // }
57 // else
58 // {
59 // return r(std::get<T>(*this));
60 // }
61 // }
62
63 template <typename Func, typename Err> auto match(Func&& f, Err&& r) noexcept
64 {
65 if (this->valid())
66 {
67 return f(std::forward<S>(std::get<S>(*this)));
68 }
69
70 return r(std::forward<T>(std::get<T>(*this)));
71 }
72};
73
74#endif
constexpr bool valid() const noexcept
Definition results.hpp:27
constexpr Result(S &&s) noexcept
Definition results.hpp:18
constexpr auto get() const noexcept -> T
Definition results.hpp:36
constexpr Result(T const &&t) noexcept
Definition results.hpp:14
auto gets() const -> S
Definition results.hpp:41
auto match(Func &&f, Err &&r) noexcept
Definition results.hpp:63
constexpr bool invalid() const noexcept
Definition results.hpp:31
constexpr Result() noexcept
Definition results.hpp:13
Definition results.hpp:8