diff options
author | Boris Kolpackov <boris@codesynthesis.com> | 2018-05-14 13:01:41 +0200 |
---|---|---|
committer | Boris Kolpackov <boris@codesynthesis.com> | 2018-05-14 13:01:41 +0200 |
commit | 12b450c33ddd804581a9212c7b88ccaa1d95b636 (patch) | |
tree | c8a6dab91091e97661773bffcd29eb10af7d2746 | |
parent | 2af1d1c2e78827b92b847c77b140dbaa9f7dc6b9 (diff) |
Add make_guard() utility
-rw-r--r-- | libbutl/utility.mxx | 40 |
1 files changed, 31 insertions, 9 deletions
diff --git a/libbutl/utility.mxx b/libbutl/utility.mxx index a431bc4..49ce5a7 100644 --- a/libbutl/utility.mxx +++ b/libbutl/utility.mxx @@ -256,28 +256,50 @@ LIBBUTL_MODEXPORT namespace butl inline reverse_range<T> reverse_iterate (T&& x) {return reverse_range<T> (std::forward<T> (x));} + // Call a function on destruction. + // + template <typename F> + struct guard_impl; + + template <typename F> + inline guard_impl<F> + make_guard (F f) + { + return guard_impl<F> (std::move (f)); + } + + template <typename F> + struct guard_impl + { + guard_impl (F f): f_ (std::move (f)) {} + ~guard_impl () {f_ ();} + + private: + F f_; + }; + // Call a function if there is an exception. // template <typename F> - struct exception_guard; + struct exception_guard_impl; template <typename F> - inline exception_guard<F> + inline exception_guard_impl<F> make_exception_guard (F f) { - return exception_guard<F> (std::move (f)); + return exception_guard_impl<F> (std::move (f)); } #ifdef __cpp_lib_uncaught_exceptions template <typename F> - struct exception_guard + struct exception_guard_impl { - exception_guard (F f) + exception_guard_impl (F f) : f_ (std::move (f)), u_ (std::uncaught_exceptions ()) {} - ~exception_guard () + ~exception_guard_impl () { if (u_ != std::uncaught_exceptions ()) f_ (); @@ -313,10 +335,10 @@ LIBBUTL_MODEXPORT namespace butl #endif template <typename F> - struct exception_guard + struct exception_guard_impl { - exception_guard (F f): f_ (std::move (f)) {} - ~exception_guard () + exception_guard_impl (F f): f_ (std::move (f)) {} + ~exception_guard_impl () { if (std::uncaught_exception ()) { |