From b8cf457e82a18233b30c696577ea57dd85aee6b8 Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Mon, 1 Apr 2019 22:09:32 +1100 Subject: [PATCH] Add Optional::map and Optional::cast methods Cool kids call that monadic interface if I understood correctly. --- src/optional.hh | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/optional.hh b/src/optional.hh index aef1a751..e6ff2b83 100644 --- a/src/optional.hh +++ b/src/optional.hh @@ -81,6 +81,26 @@ public: } const T* operator->() const { return const_cast(*this).operator->(); } + template struct DecayOptionalImpl { using Type = U; }; + template struct DecayOptionalImpl> { using Type = typename DecayOptionalImpl::Type; }; + template using DecayOptional = typename DecayOptionalImpl::Type; + + template + auto map(F f) -> Optional()))>> + { + if (not m_valid) + return {}; + return {f(m_value)}; + } + + template + auto cast() -> Optional + { + if (not m_valid) + return {}; + return {(U)m_value}; + } + template T value_or(U&& fallback) const { return m_valid ? m_value : T{std::forward(fallback)}; }