aboutsummaryrefslogtreecommitdiff
path: root/include/wanda/optional.hpp
diff options
context:
space:
mode:
authorFelix Morgner <felix.morgner@gmail.com>2018-12-11 07:42:05 +0100
committerFelix Morgner <felix.morgner@gmail.com>2018-12-11 07:42:05 +0100
commited419140280553b070943b7ba539120a26ff5686 (patch)
tree3d134977a6dfae71a45c318305166d044b50320d /include/wanda/optional.hpp
parentd3e691c9200b7b782c8acf17468068a699588a73 (diff)
downloadwanda-ed419140280553b070943b7ba539120a26ff5686.tar.xz
wanda-ed419140280553b070943b7ba539120a26ff5686.zip
wanda: restructure directory hierarchy
Diffstat (limited to 'include/wanda/optional.hpp')
-rw-r--r--include/wanda/optional.hpp65
1 files changed, 65 insertions, 0 deletions
diff --git a/include/wanda/optional.hpp b/include/wanda/optional.hpp
new file mode 100644
index 0000000..da3774c
--- /dev/null
+++ b/include/wanda/optional.hpp
@@ -0,0 +1,65 @@
+/**
+ * @file optional.hpp
+ * @author Felix Morgner (felix.morgner@gmail.com)
+ * @since 1.0.0
+ */
+
+#ifndef WANDA_OPTIONAL_HPP
+#define WANDA_OPTIONAL_HPP
+
+#include <optional>
+
+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<typename Handler>
+ 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<typename ObjectType, typename HandlerType>
+ auto with(std::optional<ObjectType> && 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