Advertisement
Radfler

::scope_guard

May 9th, 2016 (edited)
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <type_traits>
  2. #include <utility>
  3.  
  4. template<typename Callable>
  5. struct scope_guard {
  6.  
  7. public:
  8.  
  9.     static_assert(std::is_nothrow_invocable_v<Callable>, "Callable must be nothrow invocable");
  10.     static_assert(std::is_nothrow_default_constructible_v<Callable>, "Callable must be nothrow default constructible");
  11.     static_assert(std::is_nothrow_copy_constructible_v<Callable>, "Callable must be nothrow copy constructible");
  12.     static_assert(std::is_nothrow_move_constructible_v<Callable>, "Callable must be nothrow move constructible");
  13.  
  14.     constexpr explicit scope_guard() = default;
  15.    
  16.     scope_guard(const scope_guard&) = delete;
  17.     scope_guard& operator=(const scope_guard&) = delete;
  18.  
  19.     constexpr explicit scope_guard(const Callable& function) noexcept
  20.         : function(function) { }
  21.  
  22.     constexpr explicit scope_guard(Callable&& function) noexcept
  23.         : function(std::move(function)) { }
  24.  
  25.     ~scope_guard() {
  26.         function();
  27.     }
  28.  
  29. private:
  30.  
  31.     Callable function;
  32.  
  33. };
  34.  
  35. template<typename Callable>
  36. constexpr scope_guard<std::decay_t<Callable>> make_scope_guard(Callable&& callable) noexcept {
  37.     return scope_guard<std::decay_t<Callable>>{std::forward<Callable>(callable)};
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement