Switchboard SDK
Loading...
Searching...
No Matches
Result.hpp
1//
2// Result.hpp
3// SwitchboardSDK
4//
5// Created by Balazs Kiss on 2025. 01. 24..
6//
7
8#pragma once
9
10#include <any>
11#include <optional>
12#include <string>
13#include <variant>
14#include <stdexcept>
15
16namespace switchboard {
17
21struct Error {
23 std::string message;
24
30 Error(std::string msg) : message(std::move(msg)) {}
31};
32
36template <typename T>
37class Result {
38private:
39 using ValueType = std::conditional_t<std::is_void_v<T>, std::monostate, T>;
40 std::variant<ValueType, Error> result;
41
42public:
43 explicit Result(ValueType value) : result(std::move(value)) {}
44 explicit Result(Error error) : result(std::move(error)) {}
45
51 [[nodiscard]] bool isSuccess() const {
52 return std::holds_alternative<ValueType>(result);
53 }
54
60 [[nodiscard]] bool isError() const {
61 return std::holds_alternative<Error>(result);
62 }
63
69 [[nodiscard]] ValueType value() const {
70 if (!isSuccess()) {
71 throw std::runtime_error("Result does not contain a value, operation failed.");
72 }
73 return std::get<ValueType>(result);
74 }
75
81 [[nodiscard]] Error error() const {
82 if (!isError()) {
83 throw std::runtime_error("Result does not contain an error, operation was successful.");
84 }
85 return std::get<Error>(result);
86 }
87
96 [[nodiscard]] Result<std::any> toAny() const {
97 if (isSuccess()) {
98 return Result<std::any>(std::any(value()));
99 } else {
100 return Result<std::any>(Error(error().message));
101 }
102 }
103};
104
112template <typename T>
113Result<T> makeSuccess(T value) {
114 return Result<T>(std::move(value));
115}
116
122inline Result<void> makeSuccess() {
123 return Result<void>(std::monostate {});
124}
125
133template <typename T>
134Result<T> makeError(std::string errorMessage) {
135 return Result<T>(Error(std::move(errorMessage)));
136}
137
138}
Represents the result of an operation that can either succeed or fail.
Definition Result.hpp:37
bool isSuccess() const
Returns true if the operation was successful.
Definition Result.hpp:51
ValueType value() const
Returns the value of the operation if it was successful.
Definition Result.hpp:69
Result< std::any > toAny() const
Converts the result to a std::any type.
Definition Result.hpp:96
Error error() const
Returns the error of the operation if it failed.
Definition Result.hpp:81
bool isError() const
Returns true if the operation failed.
Definition Result.hpp:60
Represents an error that can occur during an operation.
Definition Result.hpp:21
std::string message
Error message.
Definition Result.hpp:23
Error(std::string msg)
Error constructor.
Definition Result.hpp:30