fork(2) download
  1. #include <iostream>
  2.  
  3. #define TRY(Expr_) \
  4.   ({ auto result = (Expr_); \
  5.   if (!result.ok) { return result; } \
  6.   std::move(result.data); })
  7.  
  8. template <typename E>
  9. struct Error {
  10. Error(E e): error(std::move(e)) {}
  11.  
  12. E error;
  13. };
  14.  
  15. template <typename E>
  16. Error<E> error(E e) { return Error<E>(std::move(e)); }
  17.  
  18. template <typename T, typename E>
  19. struct Result {
  20. template <typename U>
  21. Result(U u): ok(true), data(std::move(u)), error() {}
  22.  
  23. template <typename F>
  24. Result(Error<F> f): ok(false), data(), error(std::move(f.error)) {}
  25.  
  26. template <typename U, typename F>
  27. Result(Result<U, F>&& other):
  28. ok(other.ok), data(std::move(other.data)), error(std::move(other.error)) {}
  29.  
  30.  
  31. bool ok = false;
  32. T data;
  33. E error;
  34. };
  35.  
  36.  
  37. Result<double, std::string> sqrt(double x) {
  38. if (x < 0) {
  39. return error("sqrt does not accept negative numbers");
  40. }
  41. return x;
  42. }
  43.  
  44. Result<double, std::string> double_sqrt(double x) {
  45. auto y = TRY(sqrt(x));
  46. return sqrt(y);
  47. }
  48.  
  49. int main() {
  50. double_sqrt(4);
  51. return 0;
  52. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
Standard output is empty