scope_exit.hpp 536 B

1234567891011121314151617181920212223242526
  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. #undef CONCAT2
  10. #define CONCAT2(A, B) A##B
  11. #undef CONCAT
  12. #define CONCAT(A, B) CONCAT2(A, B)
  13. #define scope(type) scope_##type##_t CONCAT( scope_,CONCAT( type, __LINE__ ) ) = [&]()
  14. class scope_exit_t {
  15. public:
  16. template <typename F>
  17. scope_exit_t(F && fun) : _func(fun) {}
  18. scope_exit_t(scope_exit_t && other) : _func(std::move(other._func)) {}
  19. ~scope_exit_t() { _func(); }
  20. private:
  21. std::function<void()> _func;
  22. };