Created
December 29, 2018 02:03
-
-
Save jhurliman/6de7ba1610be89c9e605f7490b2e2aca to your computer and use it in GitHub Desktop.
C++ Result type wrapping std::expected and std::exception
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<typename T> | |
class [[nodiscard]] Result { | |
public: | |
Result(const T& value) : _result(value) {} | |
Result(T && value) : _result(std::move(value)) {} | |
Result(std::exception error) : _result(std::unexpected<std::exception>(std::move(error))) {} | |
bool isOk() const { | |
markChecked(); | |
return _result.has_value(); | |
} | |
void ignoreError() { | |
markChecked(); | |
} | |
constexpr const T& value() const& { | |
assert(_checked, "Unchecked value access"); | |
return _result.value(); | |
} | |
constexpr T& value()& { | |
assert(_checked, "Unchecked value access"); | |
return _result.value(); | |
} | |
constexpr T&& moveValue() { | |
assert(_checked, "Unchecked value access"); | |
return std::move(_result.value()); | |
} | |
constexpr const std::exception& error() const& { | |
return _result.error(); | |
} | |
constexpr std::exception& error()& { | |
return _result.error(); | |
} | |
private: | |
std::expected<T, std::exception> _result; | |
mutable bool _checked = false; | |
void markChecked() const { | |
_checked = true; | |
} | |
}; | |
/// Template specialization for void, a Result that does not wrap a return value. | |
template<> | |
class [[nodiscard]] Result<void> { | |
public: | |
Result() : _result() {} | |
Result(std::exception error) : _result(std::unexpected<std::exception>(std::move(error))) {} | |
~Result() { | |
assert(_checked, "Result was never checked"); | |
} | |
bool isOk() const { | |
markChecked(); | |
return _result.has_value(); | |
} | |
void ignoreError() { | |
markChecked(); | |
} | |
constexpr const std::exception& error() const& { | |
return _result.error(); | |
} | |
constexpr std::exception& error()& { | |
return _result.error(); | |
} | |
private: | |
std::expected<void, std::exception> _result; | |
mutable bool _checked = false; | |
void markChecked() const { | |
_checked = true; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment