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.
12 #ifndef LYX_REFCHANGER_H
13 #define LYX_REFCHANGER_H
15 #include "support/Changer.h"
20 /// A RefChanger records the current value of \param ref, allowing to
21 /// temporarily assign new values to it. The original value is restored
22 /// automatically when the object is destroyed, unless it is disabled.
24 /// RefChanger is movable, and doing so prolongs the duration of the temporary
25 /// assignment. This allows classes to supply their own changer methods.
27 /// Naturally, be careful not to extend the life of a RefChanger beyond that of
28 /// the reference it modifies. The RefChanger can be disabled by calling
29 /// ->keep() or ->revert(). Once disabled, the reference is never accessed
32 class RevertibleRef : public Revertible {
34 RevertibleRef(X & ref) : ref(ref), old(ref), enabled(true) {}
36 ~RevertibleRef() { revert(); }
38 void revert() { if (enabled) { enabled = false; ref = old; } }
40 void keep() { enabled = false; }
49 template <typename X> using RefChanger = unique_ptr<RevertibleRef<X>>;
52 /// Saves the value of \param ref in a movable object
53 template <typename X> RefChanger<X> make_save(X & ref)
55 return make_unique<RevertibleRef<X>>(ref);
58 /// Temporarily assign value val to reference ref.
59 /// To apply the change conditionnally, one can write:
60 /// Changer dummy = (cond) ? make_change(a, b) : Changer();
62 RefChanger<X> make_change(X & ref, X const val)
64 auto rc = make_save(ref);
73 #endif //LYX_REFCHANGER_H