Ver Fonte

refactor: add C++20 compatibility for std::uncaught_exceptions

Sam Jaffe há 6 meses atrás
pai
commit
b1e9c1a935
1 ficheiros alterados com 16 adições e 0 exclusões
  1. 16 0
      include/expect/expect.hpp

+ 16 - 0
include/expect/expect.hpp

@@ -34,15 +34,31 @@ namespace contract {
   private:
     std::function<bool()> passes_;
     std::string message_;
+#if __cpp_lib_uncaught_exceptions >= 201411L
+    int uncaught_exceptions_;
+#endif
   public:
+#if __cpp_lib_uncaught_exceptions >= 201411L
+    template <typename F>
+    ensure_t(F && passes, std::string const & msg, char const * = "")
+      : passes_(passes), message_(msg), uncaught_exceptions_(std::uncaught_exceptions()) {}
+
+    ~ensure_t() noexcept(false) {
+      if (std::uncaught_exceptions() > uncaught_exceptions_ && !passes_()) {
+        throw expect{message_};
+      }
+    }
+#else
     template <typename F>
     ensure_t(F && passes, std::string const & msg, char const * = "")
       : passes_(passes), message_(msg) {}
+
     ~ensure_t() noexcept(false) {
       if (!std::uncaught_exception() && !passes_()) {
         throw expect{message_};
       }
     }
+#endif
   };
 
   template <typename except>