4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Guillaume Munch
9 * Full author contact details are available in file CREDITS.
15 #include "support/unique_ptr.h"
21 virtual ~Revertible() = default;
24 using Changer = unique_ptr<Revertible>;
27 /// A RefChanger records the current value of \param ref, allowing to
28 /// temporarily assign new values to it. The original value is restored
29 /// automatically when the object is destroyed, unless it is disabled.
31 /// RefChanger is movable, and doing so prolongs the duration of the temporary
32 /// assignment. This allows classes to supply their own changer methods.
34 /// Naturally, be careful not to extend the life of a RefChanger beyond that of
35 /// the reference it modifies. The RefChanger can be disabled by calling
36 /// ->keep() or ->revert(). Once disabled, the reference is never accessed
39 class RevertibleRef : public Revertible {
41 RevertibleRef(X & ref) : ref(ref), old(ref), enabled(true) {}
43 ~RevertibleRef() override { revert(); }
45 void revert() { if (enabled) { enabled = false; ref = old; } }
47 void keep() { enabled = false; }
57 using RefChanger = unique_ptr<RevertibleRef<X>>;
60 /// Saves the value of \param ref in a movable object
62 inline RefChanger<X> make_save(X & ref)
64 return make_unique<RevertibleRef<X>>(ref);
67 inline Changer noChange()
72 /// Temporarily assign value val to reference ref.
73 /// To apply the change conditionally, one can write:
74 /// Changer dummy = (cond) ? changeVar(ref, val) : noChange();
76 inline RefChanger<X> changeVar(X & ref, X const val)
78 auto rc = make_save(ref);
86 #endif //LYX_CHANGER_H