fork(3) download
  1. #include <boost/optional.hpp>
  2. #include <iostream>
  3.  
  4. template<class T, class F>
  5. boost::optional<T> bind_opt(boost::optional<T> const& opt, F f){
  6. return opt ? f(opt.get()) : boost::none;
  7. }
  8.  
  9. template<class T>
  10. std::ostream& show_opt(std::ostream& os, boost::optional<T> const& opt){
  11. if(opt)
  12. return os << opt.get();
  13. return os << "None";
  14. }
  15.  
  16. typedef boost::optional<int> int_opt;
  17.  
  18. // you could make this a C++11 lambda, but
  19. // Ideone in C++11 mode doesn't have Boost
  20. int_opt test_even(int i){
  21. return (i % 2 == 0) ? int_opt(i * 3) : boost::none;
  22. }
  23.  
  24. int main(){
  25. int_opt o1 = 7;
  26. int_opt o2 = 8;
  27. int_opt o3 = boost::none;
  28. int_opt p1 = bind_opt(o1, test_even);
  29. int_opt p2 = bind_opt(o2, test_even);
  30. int_opt p3 = bind_opt(o3, test_even);
  31. show_opt(std::cout, p1) << "\n";
  32. show_opt(std::cout, p2) << "\n";
  33. show_opt(std::cout, p3) << "\n";
  34. }
Success #stdin #stdout 0.02s 2724KB
stdin
Standard input is empty
stdout
None
24
None