ORE Studio 0.0.4
Loading...
Searching...
No Matches
result.hpp
1/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * Copyright (C) 2025 Marco Craveiro <marco.craveiro@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU General Public License as published by the Free Software
7 * Foundation; either version 3 of the License, or (at your option) any later
8 * version.
9 *
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 * details.
14 *
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc., 51
17 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 *
19 */
20#ifndef ORES_COMMS_MESSAGING_RESULT_HPP
21#define ORES_COMMS_MESSAGING_RESULT_HPP
22
23#include <variant>
24#include <optional>
25
26namespace ores::comms::messaging {
27
33template<typename T, typename E>
34class result final {
35public:
36 result(const T& value) : data_(value) {}
37 result(T&& value) : data_(std::move(value)) {}
38 result(const E& error) : data_(error) {}
39 result(E&& error) : data_(std::move(error)) {}
40
41 bool has_value() const { return std::holds_alternative<T>(data_); }
42 bool has_error() const { return std::holds_alternative<E>(data_); }
43
44 explicit operator bool() const { return has_value(); }
45
46 const T& value() const & { return std::get<T>(data_); }
47 T& value() & { return std::get<T>(data_); }
48 T&& value() && { return std::get<T>(std::move(data_)); }
49
50 const T& operator*() const & { return value(); }
51 T& operator*() & { return value(); }
52 T&& operator*() && { return std::move(*this).value(); }
53
54 const T* operator->() const { return &value(); }
55 T* operator->() { return &value(); }
56
57 const E& error() const & { return std::get<E>(data_); }
58 E& error() & { return std::get<E>(data_); }
59 E&& error() && { return std::get<E>(std::move(data_)); }
60
61private:
62 std::variant<T, E> data_;
63};
64
68template<typename E>
69class result<void, E> final {
70public:
71 result() : error_(std::nullopt) {}
72 result(const E& error) : error_(error) {}
73 result(E&& error) : error_(std::move(error)) {}
74
75 bool has_value() const { return !error_.has_value(); }
76 bool has_error() const { return error_.has_value(); }
77
78 explicit operator bool() const { return has_value(); }
79
80 const E& error() const & { return *error_; }
81 E& error() & { return *error_; }
82 E&& error() && { return std::move(*error_); }
83
84private:
85 std::optional<E> error_;
86};
87
88}
89
90#endif
Contains messaging related infrastructure in the comms library.
Definition compression.hpp:29
Simple result type for C++20 (std::expected replacement).
Definition result.hpp:34