ptal / expected

What did you expect?
113 stars 18 forks source link

Add un operator||()/catch_exception #62

Closed viboes closed 10 years ago

viboes commented 10 years ago

The type of the exception can be deduced from the function parameter using the following trik

  template <class M, class E, class = if_monad_exception<decay_t<M>>>
  auto operator||(M&& m, M(*f)(E&))
  -> decltype(catch_exception<E>(std::forward<M>(m), f))
  {
    return catch_exception<E>(std::forward<M>(m), f);
  }
  template <class M, class E, class = if_monad_exception<decay_t<M>>>
  auto operator||(M&& m, std::function<M(E&)>&& f)
  -> decltype(catch_exception<E>(std::forward<M>(m), std::forward<std::function<M(E&)>>(f)))
  {
    return catch_exception<E>(std::forward<M>(m), std::forward<std::function<M(E&)>>(f));
  }
}

The use of std::function is a little bit expesive, however this will allow to do

  template <class M>
    apply<M, int> divide2(int i, int j)
  {
    using namespace boost::functional::monad_exception;
    return
    safe_divide<M>(i,j) || [](NotDivisible& e) -> apply<M, int>
        {
          return e.i / e.j;
        };
  }
viboes commented 10 years ago

https://github.com/ptal/Boost.Expected/commit/d2b3e8d0c702e0e02ffeeac3ce1a85d192f2102a