Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <exception>
- #include <stdexcept>
- #include <variant>
- #include <cstring>
- template <class T>
- class Try {
- public:
- Try() = default;
- explicit Try(const T& value) : value_(value) {
- empty_ = false;
- }
- template <typename Exception>
- explicit Try(const Exception& exception) {
- try {
- throw exception;
- } catch (const Exception& ex) {
- eptr_ = std::current_exception();
- }
- }
- const T& Value() const {
- if (eptr_) {
- std::rethrow_exception(eptr_);
- }
- if (empty_) {
- throw std::runtime_error{"Object is empty"};
- }
- return value_;
- }
- void Throw() {
- if (eptr_) {
- std::rethrow_exception(eptr_);
- }
- throw std::runtime_error{"No exception"};
- }
- bool IsFailed() const {
- if (eptr_) {
- return true;
- }
- return false;
- }
- private:
- T value_;
- std::exception_ptr eptr_;
- bool empty_ = true;
- };
- template <>
- class Try<void> {
- public:
- Try() = default;
- template <typename Exception>
- explicit Try(const Exception& exception) {
- try {
- throw exception;
- } catch (const Exception& ex) {
- eptr_ = std::current_exception();
- }
- }
- void Throw() {
- if (eptr_) {
- std::rethrow_exception(eptr_);
- }
- throw std::runtime_error{"No exception"};
- }
- bool IsFailed() const {
- if (eptr_) {
- return true;
- }
- return false;
- }
- private:
- std::exception_ptr eptr_;
- };
- template <class Function, class... Args>
- auto TryRun(Function func, Args... args) {
- using ReturnType = decltype(func(args...));
- try {
- if constexpr (std::is_void<ReturnType>::value) {
- func(args...);
- Try<ReturnType> nothing;
- return nothing;
- } else {
- Try<ReturnType> some_value(func(args...));
- return some_value;
- }
- } catch (const std::exception& ex) {
- Try<ReturnType> except(ex);
- return except;
- } catch (const char* ch) {
- Try<ReturnType> except(std::runtime_error{ch});
- return except;
- } catch (int number) {
- Try<ReturnType> except(std::strerror(number));
- return except;
- } catch (...) {
- Try<ReturnType> except(std::runtime_error{"Unknown exception"});
- return except;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement