Switchboard SDK
Loading...
Searching...
No Matches
Result.hpp
1//
2// Result.hpp
3// SwitchboardSDK
4//
5// Copyright © 2026 Synervoz. All rights reserved.
6//
7
8#pragma once
9
10#include "export.h"
11
12#include <switchboard/SBAny.hpp>
13#include <optional>
14#include <string>
15#include <variant>
16#include <stdexcept>
17
18namespace switchboard {
19
23struct SWITCHBOARDSDK_EXPORT Error {
25 std::string message;
26
32 Error(std::string msg) : message(std::move(msg)) {}
33};
34
38template <typename T>
39class SWITCHBOARDSDK_EXPORT Result {
40private:
41 using ValueType = std::conditional_t<std::is_void_v<T>, std::monostate, T>;
42 std::variant<ValueType, Error> result;
43
44public:
45 explicit Result(ValueType value) : result(std::move(value)) {}
46 explicit Result(Error error) : result(std::move(error)) {}
47
53 [[nodiscard]] bool isSuccess() const {
54 return std::holds_alternative<ValueType>(result);
55 }
56
62 [[nodiscard]] bool isError() const {
63 return std::holds_alternative<Error>(result);
64 }
65
71 [[nodiscard]] ValueType value() const {
72 if (!isSuccess()) {
73 throw std::runtime_error("Result does not contain a value, operation failed.");
74 }
75 return std::get<ValueType>(result);
76 }
77
83 [[nodiscard]] Error error() const {
84 if (!isError()) {
85 throw std::runtime_error("Result does not contain an error, operation was successful.");
86 }
87 return std::get<Error>(result);
88 }
89
98 [[nodiscard]] Result<SBAny> toAny() const {
99 if (isSuccess()) {
100 return Result<SBAny>(SBAny(value()));
101 } else {
102 return Result<SBAny>(Error(error().message));
103 }
104 }
105};
106
114template <typename T>
115Result<T> makeSuccess(T value) {
116 return Result<T>(std::move(value));
117}
118
124inline Result<void> makeSuccess() {
125 return Result<void>(std::monostate {});
126}
127
135template <typename T>
136Result<T> makeError(std::string errorMessage) {
137 return Result<T>(Error(std::move(errorMessage)));
138}
139
140}
Represents the result of an operation that can either succeed or fail.
Definition Result.hpp:39
bool isSuccess() const
Returns true if the operation was successful.
Definition Result.hpp:53
ValueType value() const
Returns the value of the operation if it was successful.
Definition Result.hpp:71
Result< SBAny > toAny() const
Converts the result to a SBAny type.
Definition Result.hpp:98
Error error() const
Returns the error of the operation if it failed.
Definition Result.hpp:83
bool isError() const
Returns true if the operation failed.
Definition Result.hpp:62
A versatile container class that can hold values of various types.
Definition SBAny.hpp:53
Represents an error that can occur during an operation.
Definition Result.hpp:23
std::string message
Error message.
Definition Result.hpp:25
Error(std::string msg)
Error constructor.
Definition Result.hpp:32