fork download
  1. #include <utility>
  2. #include <iostream>
  3. #include <boost/optional.hpp>
  4.  
  5. template <typename T>
  6. auto trycatch(T t) {
  7. return [f = std::move(t)](auto&&... args) {
  8. using rettype = decltype(f(std::forward<decltype(args)>(args)...));
  9. try {
  10. return boost::optional<rettype>(f(std::forward<decltype(args)>(args)...));
  11. }
  12. catch(...)
  13. {
  14. return boost::optional<rettype>{};
  15. }
  16.  
  17. };
  18. }
  19.  
  20. int access_resource1()
  21. {
  22. throw std::runtime_error("");
  23. }
  24.  
  25. int access_resource2()
  26. {
  27. throw std::runtime_error("");
  28. }
  29.  
  30. int calculate_smth()
  31. {
  32. constexpr auto default_value = 42;
  33.  
  34. auto val = trycatch(access_resource1)();
  35. if(!val)
  36. {
  37. val = trycatch(access_resource2)();
  38. }
  39.  
  40. if(!val)
  41. {
  42. val = default_value;
  43. }
  44.  
  45. return *val;
  46. }
  47.  
  48. int main() {
  49. std::cout << calculate_smth() << std::endl;
  50. }
  51.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
42