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) const noexcept
51 // {
52 // if (this->valid())
53 // {
54 // return f(std::get<S>(*this));
55 // }
56 // else
57 // {
58 // return r(std::get<T>(*this));
59 // }
60 // }
61
62 template <typename Func, typename Err> auto match(Func&& f, Err&& r) noexcept
63 {
64 if (this->valid())
65 {
66 return f(std::forward<S>(std::get<S>(*this)));
67 }
68
69 return r(std::forward<T>(std::get<T>(*this)));
70 }
71};
72
73#endif
Definition results.hpp:12
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:62
constexpr bool invalid() const noexcept
Definition results.hpp:31
constexpr Result() noexcept
Definition results.hpp:13
Definition results.hpp:8