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; }
50 #if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 6)
52 struct RefChanger : unique_ptr<RevertibleRef<X>>
54 RefChanger(unique_ptr<RevertibleRef<X>> p)
55 : unique_ptr<RevertibleRef<X>>(move(p))
59 template <typename X> using RefChanger = unique_ptr<RevertibleRef<X>>;
63 /// Saves the value of \param ref in a movable object
64 template <typename X> RefChanger<X> make_save(X & ref)
66 return make_unique<RevertibleRef<X>>(ref);
69 /// Temporarily assign value val to reference ref.
70 /// To apply the change conditionnally, one can write:
71 /// Changer dummy = (cond) ? make_change(a, b) : Changer();
73 RefChanger<X> make_change(X & ref, X const val)
75 auto rc = make_save(ref);
84 #endif //LYX_REFCHANGER_H