Last active
August 29, 2015 14:06
-
-
Save piyo7/439e7da8866c12330047 to your computer and use it in GitHub Desktop.
boost::optionalにモナドのbindを ref: http://qiita.com/piyo7/items/6871e6fe0c4fb9198349
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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