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

前端 未结 5 1028
隐瞒了意图╮
隐瞒了意图╮ 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:47

    I was the OP (lost my account when SO migrated). Here is the latest I came up with using std::invoke. Life becomes much simpler

    template < typename T >
    auto operator | (Maybe < T > const & v, auto && f)
    {
        using U = std::decay_t < decltype(f(v.get())) >;
        if (v.isNull())
            return Maybe < U >::nothing();
        else
            return Maybe < U >::just(std::invoke(f, v.get()));
    }
    
    template < typename T >
    auto operator | (Maybe < T > & v, auto && f)
    {
        using U = std::decay_t < decltype(f(v.get())) >;
        if (v.isNull())
            return Maybe < U >::nothing();
        else
            return Maybe < U >::just(std::invoke(f, v.get()));
    }
    
    template < typename T >
    auto operator | (Maybe < T > && v, auto && f)
    {
        using U = std::decay_t < decltype(f(v.get())) >;
        if (v.isNull())
            return Maybe < U >::nothing();
        else
            return Maybe < U >::just(std::invoke(f, v.get()));
    }
    

提交回复
热议问题