scoped_state.h 688 B

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