7
7

More than 5 years have passed since last update.

boost::optionalにモナドのbindを

Last updated at Posted at 2014-09-27

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;
}

実行結果:[Wandbox]三へ( へ՞ਊ ՞)へ ハッハッ

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7