magpie
Loading...
Searching...
No Matches
Result.hpp
1#pragma once
2
3#include <stdexcept>
4#include <variant>
5
6namespace magpie {
7
8template <typename T, typename ERR>
9struct Result {
10private:
11 using InternalType = std::variant<T, ERR>;
12 const InternalType held;
13
14 Result(InternalType&& value)
15 : held(std::move(value)) {}
16
17public:
18 const T* operator->() const {
19 if (held.index() != 0) {
20 throw std::runtime_error("Illegal access into error result");
21 }
22
23 return &(std::get<T>(held));
24 }
25
26 bool isOk() const { return held.index() == 0; }
27 bool isError() const { return held.index() == 1; }
28
29 const T& unwrap() { return std::get<0>(held); }
30 const ERR& error() { return std::get<1>(held); }
31
32 static Result<T, ERR> ok(T&& value) {
33 return Result(InternalType(std::in_place_index<0>, std::move(value)));
34 }
35 static Result<T, ERR> err(ERR&& value) {
36 return Result(InternalType(std::in_place_index<1>, std::move(value)));
37 }
38};
39
40}