scoped_state.h 530 B

123456789101112131415161718192021222324
  1. #pragma once
  2. #include <functional>
  3. #define CONCAT2(A, B) A##B
  4. #define CONCAT(A, B) CONCAT2(A, B)
  5. #define scoped_state(prop, value) auto CONCAT(scoped_state_, __LINE__) = ScopedState(prop, value)
  6. namespace jvalidate::detail {
  7. class ScopedState {
  8. private:
  9. std::function<void()> reset_;
  10. public:
  11. template <typename T>
  12. ScopedState(T & prop, T value) : reset_([reset = prop, &prop]() { prop = reset; }) {
  13. prop = std::move(value);
  14. }
  15. ~ScopedState() { reset_(); }
  16. explicit operator bool() const { return true; }
  17. };
  18. }