scope_exit.hpp 459 B

123456789101112131415161718192021222324
  1. //
  2. // scope_exit.hpp
  3. // gameutils
  4. //
  5. // Created by Sam Jaffe on 7/5/16.
  6. //
  7. #pragma once
  8. #include <functional>
  9. #include "macro.h"
  10. #define scope(type) scope_##type##_t CONCAT(scope_,CONCAT(type,__LINE__) = [&]()
  11. class scope_exit_t {
  12. public:
  13. template <typename F>
  14. scope_exit_t(F && fun) : _func(fun) {}
  15. scope_exit_t(scope_exit_t && other) : _func(std::move(other._func)) {}
  16. ~scope_exit_t() { _func(); }
  17. private:
  18. std::function<void()> _func;
  19. };