Adds new result class to show a functions success or failure.
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
This commit is contained in:
parent
0116ed8f4c
commit
f7a161c690
|
@ -0,0 +1,58 @@
|
|||
#ifndef ARBUTILS_RESULT_HPP
|
||||
#define ARBUTILS_RESULT_HPP
|
||||
|
||||
namespace ArbUt {
|
||||
/// @brief Whether the result was okay, or was an error
|
||||
enum class ResultStatus : uint8_t { Ok, Error };
|
||||
|
||||
/// @brief Simple data class to return a functions success or failure.
|
||||
/// @tparam T The potential return value of the function.
|
||||
template <class T> class Result<T> {
|
||||
public:
|
||||
/// @brief Return a success, along with the success value.
|
||||
/// @param value The value to return.
|
||||
/// @return The result class
|
||||
inline static const Result& Ok(T value) { return Result(ResultStatus::Ok, value); }
|
||||
/// @brief Return an error, along with an error message.
|
||||
/// @param message The error message to return
|
||||
/// @return The result class
|
||||
inline static const Result& Error(const std::string& message) { return Result(message); }
|
||||
|
||||
/// @brief Returns whether or not the function succeeded,
|
||||
/// @return Whether or not the function succeeded.
|
||||
[[nodiscard]] inline ResultStatus GetStatus() const noexcept { return _resultStatus; }
|
||||
|
||||
/// @brief The value of the result if it was successful.
|
||||
/// @return The value of the result if it was successful.
|
||||
inline const T& GetValue() const noexcept {
|
||||
Assert(_resultStatus == ResultStatus::Ok);
|
||||
return _resultValue;
|
||||
}
|
||||
|
||||
/// @brief The value of the result if it was successful.
|
||||
/// @return The value of the result if it was successful.
|
||||
inline T& GetValue() noexcept {
|
||||
Assert(_resultStatus == ResultStatus::Ok);
|
||||
return _resultValue;
|
||||
}
|
||||
|
||||
/// @brief Returns the error message if it errored.
|
||||
/// @return The error message if it errored.
|
||||
[[nodiscard]] inline const std::string& GetErrorMessage() const noexcept {
|
||||
Assert(_resultStatus == ResultStatus::Error);
|
||||
return _errorMessage;
|
||||
}
|
||||
|
||||
private:
|
||||
Result(ResultStatus result, const T& value) : _resultStatus(result), _resultValue(value) {}
|
||||
explicit Result(const std::string& error) : _resultStatus(ResultStatus::Error), _errorMessage(error) {}
|
||||
|
||||
ResultStatus _resultStatus;
|
||||
union {
|
||||
T _resultValue;
|
||||
std::string _errorMessage{};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
#endif // ARBUTILS_RESULT_HPP
|
Loading…
Reference in New Issue