DeferralActionWrapper.hpp 1.13 KB
Newer Older
Martin Kröning's avatar
Martin Kröning committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#pragma once

#include <functional>
#include <vector>

/// Wraps an object and defers modifying actions
/// until explicitly applying them
///
/// \param T The type of the wrapped object
template <typename T> class DeferralActionWrapper {
public:
  using ValueType = T;
  using Function = std::function<void(ValueType &)>;

  /// Constructs a wrapper around a default constructed object
  DeferralActionWrapper() = default;

  /// Constructs a wrapper around a given \p object
  explicit DeferralActionWrapper(ValueType object)
      : wrappedObject(std::move(object)) {}

  /// Returns a the wrapped object
  ValueType &get() { return wrappedObject; }
  const ValueType &get() const { return wrappedObject; }

  /// Enqueues an \p action
  ///
  /// Caution: Be sure to work on a reference to modify the wrapped object!
  void enqueue(Function action) {
    deferredActions.push_back(std::move(action));
  }

  /// Applies pending modifying actions
  void apply() {
    for (auto &&action : deferredActions) {
      action(wrappedObject);
    }
    deferredActions.clear();
  }

private:
  ValueType wrappedObject;
  std::vector<Function> deferredActions;
};