Advertisement
Art_Uspen

Untitled

Oct 14th, 2021
1,256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. template <class T>
  2. class Try {
  3. public:
  4.     Try() : value_(T()), is_take_ex_(false){};
  5.     Try(T value) : value_(value), is_take_ex_(false) {
  6.     }
  7.     template <typename EX>
  8.     Try(EX&& ex) : value_(T()), is_take_ex_(true), ex_(std::make_exception_ptr(ex)) {
  9.     }
  10.  
  11.     const T& Value() const {
  12.         if (is_take_ex_) {
  13.             std::rethrow_exception(ex_);
  14.         } else if (value_ == T()) {
  15.             throw std::runtime_error("Object is empty");
  16.         } else {
  17.             return value_;
  18.         }
  19.     }
  20.     void Throw() {
  21.         if (is_take_ex_) {
  22.             std::rethrow_exception(ex_);
  23.         } else {
  24.             throw std::runtime_error("No exception");
  25.         }
  26.     }
  27.     bool IsFailed() const {
  28.         return is_take_ex_;
  29.     }
  30.     ~Try() = default;
  31.  
  32. protected:
  33.     T value_= T();
  34.     bool is_take_ex_ = false;
  35.     std::exception_ptr ex_;
  36. };
  37.  
  38. template <>
  39. class Try<void> : private Try<int> {
  40. public:
  41.     Try<void>() = default;
  42.  
  43.     //    using Try<int>::Try<int>;
  44.     template <typename EX>
  45.     Try<void>(EX&& ex) : is_take_ex_(true), ex_(std::make_exception_ptr(ex)) {
  46.     }
  47.     using Try<int>::Throw;
  48.     using Try<int>::IsFailed;
  49.     ~Try<void>() = default;
  50.  
  51. private:
  52.         bool is_take_ex_;
  53.         std::exception_ptr ex_;
  54. };
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement