Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template <class T>
- class Try {
- public:
- Try() : value_(T()), is_take_ex_(false){};
- Try(T value) : value_(value), is_take_ex_(false) {
- }
- template <typename EX>
- Try(EX&& ex) : value_(T()), is_take_ex_(true), ex_(std::make_exception_ptr(ex)) {
- }
- const T& Value() const {
- if (is_take_ex_) {
- std::rethrow_exception(ex_);
- } else if (value_ == T()) {
- throw std::runtime_error("Object is empty");
- } else {
- return value_;
- }
- }
- void Throw() {
- if (is_take_ex_) {
- std::rethrow_exception(ex_);
- } else {
- throw std::runtime_error("No exception");
- }
- }
- bool IsFailed() const {
- return is_take_ex_;
- }
- ~Try() = default;
- protected:
- T value_= T();
- bool is_take_ex_ = false;
- std::exception_ptr ex_;
- };
- template <>
- class Try<void> : private Try<int> {
- public:
- Try<void>() = default;
- // using Try<int>::Try<int>;
- template <typename EX>
- Try<void>(EX&& ex) : is_take_ex_(true), ex_(std::make_exception_ptr(ex)) {
- }
- using Try<int>::Throw;
- using Try<int>::IsFailed;
- ~Try<void>() = default;
- private:
- bool is_take_ex_;
- std::exception_ptr ex_;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement