From 12b450c33ddd804581a9212c7b88ccaa1d95b636 Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Mon, 14 May 2018 13:01:41 +0200 Subject: Add make_guard() utility --- libbutl/utility.mxx | 40 +++++++++++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 9 deletions(-) (limited to 'libbutl/utility.mxx') 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 reverse_iterate (T&& x) {return reverse_range (std::forward (x));} + // Call a function on destruction. + // + template + struct guard_impl; + + template + inline guard_impl + make_guard (F f) + { + return guard_impl (std::move (f)); + } + + template + 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 - struct exception_guard; + struct exception_guard_impl; template - inline exception_guard + inline exception_guard_impl make_exception_guard (F f) { - return exception_guard (std::move (f)); + return exception_guard_impl (std::move (f)); } #ifdef __cpp_lib_uncaught_exceptions template - 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 - 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 ()) { -- cgit v1.1