DNDSR 0.1.0.dev1+gcd065ad
Distributed Numeric Data Structure for CFV
Loading...
Searching...
No Matches
ScopedValueAlternator.hpp
Go to the documentation of this file.
1#pragma once
2/// @file ScopedValueAlternator.hpp
3/// @brief RAII helper that temporarily overrides a variable and restores its
4/// original value when the scope exits.
5
6namespace DNDS
7{
8 /**
9 * @brief RAII sentinel: on construction replaces `ref` with a new value
10 * and on destruction restores the original value.
11 *
12 * @details Useful for surgically changing a global / member flag for the
13 * duration of a function without adding explicit try/catch cleanup:
14 * ```cpp
15 * {
16 * ScopedValueAlternator<bool> g(DNDS::Debug::isDebugging, true);
17 * runDiagnostics();
18 * } // isDebugging restored here, even on exception
19 * ```
20 *
21 * Move/copy are not declared; an instance must stay in the scope that
22 * owns the reference.
23 *
24 * @tparam T Any assignable type.
25 */
26 template <class T>
28 {
29 T &ref_;
30 T old_tmp_;
31
32 public:
33 /// @brief Save the current value of `ref` and overwrite it with `vAssign`.
34 template <class TAssign>
35 ScopedValueAlternator(T &ref, TAssign &&vAssign) : ref_(ref), old_tmp_(ref_)
36 {
37 ref_ = vAssign;
38 }
39
41 {
42 ref_ = old_tmp_;
43 }
44 };
45}
RAII sentinel: on construction replaces ref with a new value and on destruction restores the original...
ScopedValueAlternator(T &ref, TAssign &&vAssign)
Save the current value of ref and overwrite it with vAssign.
the host side operators are provided as implemented