Created
February 27, 2014 15:10
-
-
Save loosechainsaw/9251921 to your computer and use it in GitHub Desktop.
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 <memory> | |
template<class T> | |
class Option{ | |
public: | |
Option() : value_(nullptr){ | |
} | |
Option(T const& value) : value_(std::move(value)){ | |
} | |
Option(T&& value) : value_(std::make_shared<T>(std::move(value))){ | |
} | |
Option(Option const&) = default; | |
Option(Option&&) = default; | |
Option& operator = (Option const&) = default; | |
Option& operator = (Option&&) = default; | |
template<class Function> | |
auto fmap(Function func) -> Option<decltype(func( std::declval<T>() ))>{ | |
return Option<decltype(func( std::declval<T>() ))>(func(*value_)); | |
} | |
template<class Function> | |
auto operator >>= (Function func) -> decltype(func( std::declval<T>() )){ | |
if(value_ == nullptr) | |
return decltype(func( std::declval<T>() ))(); | |
return func(*value_); | |
} | |
void foreach(std::function<void ( T const& ) > func){ | |
if(value_ != nullptr) | |
return func(*value_); | |
} | |
static Option<T> Unit(T const& value){ | |
return Option<T>(value); | |
} | |
static Option<T> Unit(T&& value){ | |
return Option<T>(std::move(value)); | |
} | |
static Option<T> None(){ | |
return Option<T>(); | |
} | |
private: | |
std::shared_ptr<T> value_; | |
}; | |
Option<int> function1(){ | |
return Option<int>::Unit(10); | |
} | |
Option<int> function2(int value){ | |
if(value >= 10){ | |
return Option<int>::Unit(value * 10); | |
} | |
return Option<int>::None(); | |
} | |
Option<double> function3(int value){ | |
return Option<double>(value * 10); | |
} | |
int main(int argc, const char * argv[]) | |
{ | |
auto result = (function1() >>= function2) >>= function3; | |
result.foreach([](double const& a){ | |
std::cout << a << std::endl; | |
}); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment