on_block_exit.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #pragma once
  2. #include <functional>
  3. namespace jvalidate::detail {
  4. /**
  5. * @brief An object representing a cleanup function, to be called as if it was
  6. * a destructor for the current function scope. Similar to e.g. D-lang's
  7. * scope(exit) or @see https://en.cppreference.com/w/cpp/experimental/scope_exit
  8. *
  9. * Is movable - allowing us to return this scope object from its constructing
  10. * context into the actual owning context that wants to control that scope.
  11. */
  12. class OnBlockExit {
  13. private:
  14. std::function<void()> callback_;
  15. public:
  16. OnBlockExit() = default;
  17. template <typename F> OnBlockExit(F && callback) : callback_(callback) {}
  18. // Must be explicity implemented because function's move ctor is non-destructive
  19. OnBlockExit(OnBlockExit && other) { std::swap(other.callback_, callback_); }
  20. // Must be explicity implemented because function's move-assign is non-destructive
  21. OnBlockExit & operator=(OnBlockExit && other) {
  22. std::swap(other.callback_, callback_);
  23. return *this;
  24. }
  25. ~OnBlockExit() {
  26. if (callback_) {
  27. callback_();
  28. }
  29. }
  30. };
  31. }