C++のboost::optionalを、HaskellのMaybeモナドみたいに使い隊。
#include <iostream>
#include <type_traits>
#include <boost/optional.hpp>
template <
typename Input,
typename Functor,
typename OptionalOutput = typename std::result_of<Functor(Input)>::type
>
OptionalOutput operator >>= (
const boost::optional<Input>& a,
Functor f
) {
if (a) return f(*a);
return boost::none;
}
template<typename T>
std::ostream& operator<<(std::ostream& os, const boost::optional<T>& a) {
if (a) return os << *a;
else return os << "none";
}
int main() {
auto f = [](bool b){ return b ? boost::optional<int>(42) : boost::none; };;
std::cout << (boost::optional<bool>(true) >>= f) << std::endl; // 42
std::cout << (boost::optional<bool>(false) >>= f) << std::endl; // none
std::cout << (boost::optional<bool>() >>= f) << std::endl; // none
//std::cout << (boost::none >>= f) << std::endl; // boost::none使うと型推論できなくて残念
return 0;
}