Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <exception>
- #include <stdexcept>
- #include <cstring>
- #include <cassert>
- #include <string>
- struct Slug {};
- template <class T>
- class Try {
- public:
- Try() {
- }
- Try(T value) : value(value), empty(false) {
- }
- template <typename Ex>
- Try(const Ex& ex) {
- try {
- throw ex;
- } catch(...) {
- eptr = std::current_exception();
- }
- }
- Try(std::exception_ptr ep) : eptr(ep) {
- }
- template <typename Ex>
- Try(T value, const Ex& ex) : value(value), empty(false) {
- try {
- throw ex;
- } catch(...) {
- eptr = std::current_exception();
- }
- }
- const T& Value() {
- if (eptr) {
- std::rethrow_exception(eptr);
- } else if (empty) {
- throw std::runtime_error("Object is empty");
- }
- return value;
- }
- virtual void Throw() {
- if (eptr) {
- std::rethrow_exception(eptr);
- } else {
- throw std::runtime_error("No exception");
- }
- }
- bool IsFailed() {
- if (eptr) {
- return true;
- } else {
- return false;
- }
- }
- private:
- bool empty = true;
- T value;
- std::exception_ptr eptr;
- };
- template <>
- class Try<void> : private Try<Slug> {
- public:
- Try() {
- }
- template <typename Exv>
- Try(const Exv& exv) : Try<Slug>(exv) {
- }
- Try(std::exception_ptr ep) : Try<Slug>(ep) {
- }
- void Throw() {
- Try<Slug>::Throw();
- }
- bool IsFailed() {
- return Try<Slug>::IsFailed();
- }
- };
- template <class Function, class... Args>
- auto TryRun(Function func, Args... args) {
- using ReturnType = decltype(func(args...));
- try {
- func(args...);
- if constexpr(std::is_same<ReturnType, void>::value) {
- return Try<void>();
- } else {
- return Try<ReturnType>(func(args...));
- }
- } catch(std::exception& e) {
- if constexpr(std::is_same<ReturnType, void>::value) {
- return Try<void>(std::current_exception);
- } else {
- return Try<ReturnType>(std::current_exception);
- }
- } catch(const char* str) {
- std::runtime_error e(str);
- if constexpr(std::is_same<ReturnType, void>::value) {
- return Try<void>(e);
- } else {
- return Try<ReturnType>(e);
- }
- } catch(int i) {
- std::runtime_error e(std::strerror(i));
- if constexpr(std::is_same<ReturnType, void>::value) {
- return Try<void>(e);
- } else {
- return Try<ReturnType>(e);
- }
- } catch(...) {
- std::runtime_error e("Unknown exception");
- if constexpr(std::is_same<ReturnType, void>::value) {
- return Try<void>(e);
- } else {
- return Try<ReturnType>(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement