From 577fc0845718ed8ad5bebf02a277c0579a817f77 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 17 May 2024 17:58:38 +0200 Subject: wanda: restructure source layout --- source/lib/include/wanda/std_ext/optional.hpp | 65 +++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 source/lib/include/wanda/std_ext/optional.hpp (limited to 'source/lib/include/wanda/std_ext/optional.hpp') diff --git a/source/lib/include/wanda/std_ext/optional.hpp b/source/lib/include/wanda/std_ext/optional.hpp new file mode 100644 index 0000000..763e8ac --- /dev/null +++ b/source/lib/include/wanda/std_ext/optional.hpp @@ -0,0 +1,65 @@ +/** + * @file optional.hpp + * @author Felix Morgner (felix.morgner@gmail.com) + * @since 1.0.0 + */ + +#ifndef WANDA_STD_EXT_OPTIONAL_HPP +#define WANDA_STD_EXT_OPTIONAL_HPP + +#include + +namespace wanda::std_ext +{ + /** + * @brief A type to represent a computation that could fail + */ + struct failable + { + /** + * @brief A factory to create a successful computation + */ + constexpr static auto success() { return failable{false}; } + + /** + * @brief A factory to create a failed computation + */ + constexpr static auto failure() { return failable{true}; } + + /** + * @brief Execute the given handler if the computation failed + */ + template + constexpr void operator||(Handler handler) const + { + if (m_failed) + { + handler(); + } + } + + private: + constexpr explicit failable(bool failed) + : m_failed{failed} {}; + bool const m_failed; + }; + + /** + * @brief Unwrap the given optional object, if present, and pass it to the handler + * + * @return A successful computation iff. the object was present, a failed computation otherwise. + */ + template + auto with(std::optional && object, HandlerType handler) + { + if (object) + { + handler(object.value()); + return failable::success(); + } + return failable::failure(); + } + +} // namespace wanda::std_ext + +#endif \ No newline at end of file -- cgit v1.2.3