aboutsummaryrefslogtreecommitdiff
path: root/src/optional.hpp
blob: da3774c0d4be8861810edf1fe704776f7bd3a600 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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