Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <type_traits>
- #include <utility>
- template<typename Callable>
- struct scope_guard {
- public:
- static_assert(std::is_nothrow_invocable_v<Callable>, "Callable must be nothrow invocable");
- static_assert(std::is_nothrow_default_constructible_v<Callable>, "Callable must be nothrow default constructible");
- static_assert(std::is_nothrow_copy_constructible_v<Callable>, "Callable must be nothrow copy constructible");
- static_assert(std::is_nothrow_move_constructible_v<Callable>, "Callable must be nothrow move constructible");
- constexpr explicit scope_guard() = default;
- scope_guard(const scope_guard&) = delete;
- scope_guard& operator=(const scope_guard&) = delete;
- constexpr explicit scope_guard(const Callable& function) noexcept
- : function(function) { }
- constexpr explicit scope_guard(Callable&& function) noexcept
- : function(std::move(function)) { }
- ~scope_guard() {
- function();
- }
- private:
- Callable function;
- };
- template<typename Callable>
- constexpr scope_guard<std::decay_t<Callable>> make_scope_guard(Callable&& callable) noexcept {
- return scope_guard<std::decay_t<Callable>>{std::forward<Callable>(callable)};
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement