Implementing Haskell's Maybe Monad in c++11

后端 未结 6 1507
星月不相逢
星月不相逢 2021-01-31 09:54

I am trying to implement the Maybe monad from Haskell using the lambda functions in C++11 and templates. Here\'s what I have so far

#include
#i         


        
6条回答
  •  萌比男神i
    2021-01-31 10:47

    The type of a lambda isn't a specialization of std::function. It's some unamed type. There is a conversion to std::function, but that means type deduction won't work for it. So, in this call:

    Maybe p = (x >>= z);
    

    The type T2 can't be deduced:

    Maybe operator>>=(Maybe t, std::function < Maybe (T1)> &f)
    

    Store the lambda in a std::function variable from the start, and it should work:

    std::function < Maybe (int)> z = [](int a) -> Maybe { ... };
    

    However, it's probably easier to accept any kind of function object. That way you can still use auto for the lambda.

    template
    typename std::result_of::type
    operator>>=(Maybe t, F&& f) {
        ... std::forward(f)(t.data);
    }
    

提交回复
热议问题