Skip to content

Instantly share code, notes, and snippets.

@piyo7
Last active August 29, 2015 14:06
Show Gist options
  • Save piyo7/439e7da8866c12330047 to your computer and use it in GitHub Desktop.
Save piyo7/439e7da8866c12330047 to your computer and use it in GitHub Desktop.
boost::optionalにモナドのbindを ref: http://qiita.com/piyo7/items/6871e6fe0c4fb9198349
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment