Haskell style “Maybe” type & *chaining* in C++11

前端 未结 5 1251
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 20:43

I repeatedly find myself requiring Haskell style Maybe (especially Maybe chaining) in my project at work. E.g. withdrawal request from customer and we are give

5条回答
  •  粉色の甜心
    2020-12-23 21:36

    As a recovering template-aholic, I feel it my duty to point out the simple non-template exception-based solution for the given example.

    Adjust the code to throw an exception instead of returning Maybe/Optional, and the code becomes...

    try
    {
      print(getBalance(getCheckingAccount(getCustomer(customers, "12346"))));
    }
    catch(my_error_t) 
    {}
    

    That's not to say Maybe/Optional monads are never useful in C++, but for many cases exceptions will get things done in a much more idiomatic and easily understood manner.

提交回复
热议问题