Implementing Haskell's Maybe Monad in c++11

后端 未结 6 1498
星月不相逢
星月不相逢 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条回答
  •  情深已故
    2021-01-31 10:54

    The following works for me: I use decltype to infer the type returned by the lambda:

    template    
    auto operator>>=(Maybe t, Func f) -> decltype(f(t.data))
    {    
      decltype(f(t.data)) return_value;    
      if(t.valid == false)    
      {            
        return_value.valid = false;    
        return return_value;    
      }    
      else    
      {            
        return f(t.data);    
      }                
    }
    

    EDIT

    For type safety :

    template    
    struct Maybe    
    {    
      T1 data;    
      bool valid;
    
      static const bool isMaybe = true;
    };
    
    template     
    auto operator>>=(Maybe t, Func f) -> decltype(f(t.data)) 
    {
      typedef decltype(f(t.data)) RT;
      static_assert(RT::isMaybe, "F doesn't return a maybe");
      ...
    

提交回复
热议问题