Added result type and stacktrace capabilities.
This commit is contained in:
75
source/mijin/types/result.hpp
Normal file
75
source/mijin/types/result.hpp
Normal file
@@ -0,0 +1,75 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#if !defined(MIJIN_TYPES_RESULT_HPP_INCLUDED)
|
||||
#define MIJIN_TYPES_RESULT_HPP_INCLUDED 1
|
||||
|
||||
#include <string>
|
||||
#include <variant>
|
||||
|
||||
namespace mijin
|
||||
{
|
||||
|
||||
//
|
||||
// public defines
|
||||
//
|
||||
|
||||
//
|
||||
// public constants
|
||||
//
|
||||
|
||||
//
|
||||
// public types
|
||||
//
|
||||
|
||||
template<typename TSuccess, typename TError>
|
||||
class ResultBase
|
||||
{
|
||||
private:
|
||||
struct Empty {};
|
||||
|
||||
std::variant<Empty, TSuccess, TError> state_;
|
||||
public:
|
||||
ResultBase() = default;
|
||||
ResultBase(const ResultBase&) = default;
|
||||
ResultBase(ResultBase&&) = default;
|
||||
ResultBase(TSuccess successValue) noexcept : state_(std::move(successValue)) {}
|
||||
ResultBase(TError errorValue) noexcept : state_(std::move(errorValue)) {}
|
||||
|
||||
ResultBase& operator=(const ResultBase&) = default;
|
||||
ResultBase& operator=(ResultBase&&) = default;
|
||||
|
||||
bool operator==(const ResultBase& other) const noexcept { return state_ == other.state_; }
|
||||
bool operator!=(const ResultBase& other) const noexcept { return state_ != other.state_; }
|
||||
operator bool() const noexcept { return isSuccess(); }
|
||||
bool operator!() const noexcept { return !isSuccess(); }
|
||||
TSuccess& operator*() noexcept { return getValue(); }
|
||||
const TSuccess& operator*() const noexcept { return getValue(); }
|
||||
TSuccess* operator->() noexcept { return &getValue(); }
|
||||
const TSuccess* operator->() const noexcept { return &getValue(); }
|
||||
|
||||
[[nodiscard]] bool isEmpty() const noexcept { return std::holds_alternative<Empty>(state_); }
|
||||
[[nodiscard]] bool isSuccess() const noexcept { return std::holds_alternative<TSuccess>(state_); }
|
||||
[[nodiscard]] bool isError() const noexcept { return std::holds_alternative<TError>(state_); }
|
||||
|
||||
[[nodiscard]] TSuccess& getValue() noexcept { return std::get<TSuccess>(state_); }
|
||||
[[nodiscard]] TError& getError() noexcept { return std::get<TError>(state_); }
|
||||
[[nodiscard]] const TSuccess& getValue() const noexcept { return std::get<TSuccess>(state_); }
|
||||
[[nodiscard]] const TError& getError() const noexcept { return std::get<TError>(state_); }
|
||||
};
|
||||
|
||||
struct ResultError
|
||||
{
|
||||
std::string message;
|
||||
};
|
||||
|
||||
template<typename TSuccess>
|
||||
using Result = ResultBase<TSuccess, ResultError>;
|
||||
|
||||
//
|
||||
// public functions
|
||||
//
|
||||
|
||||
} // namespace mijin
|
||||
|
||||
#endif // !defined(MIJIN_TYPES_RESULT_HPP_INCLUDED)
|
||||
Reference in New Issue
Block a user