SUNphi  1.0
ScopeDoer.hpp
Go to the documentation of this file.
1 #ifndef _SCOPEDOER_HPP
2 #define _SCOPEDOER_HPP
3 
4 /// \file ScopeDoer.hpp
5 ///
6 /// \brief Scope-based action
7 
8 #include <utility>
9 
10 namespace SUNphi
11 {
12  /// Class which does something when created and something else when destroyed
13  ///
14  /// The action performed at the beginning must return whether the
15  /// action had an effect or not, such that the undo is issued or not
16  /// at the destruction. The action performed at the end needs not to
17  /// return anything (can return whatever).
18  template <typename FEnd> // Type of the function which is called at destruction
19  class [[ nodiscard ]] ScopeDoer
20  {
21  /// Function to be called at destroy
22  FEnd fEnd;
23 
24  /// Store whether we need to undo at the end
25  bool undoAtEnd;
26 
27  /// Forbids copy constructor
28  ScopeDoer(const ScopeDoer&) = delete;
29 
30  public:
31 
32  /// Check if will undo
33  bool willUndo()
34  const
35  {
36  return
37  undoAtEnd;
38  }
39 
40  /// Move constructor
41  ScopeDoer(ScopeDoer&& oth) :
42  fEnd(std::move(oth.fEnd)),
43  undoAtEnd(oth.undoAtEnd)
44  {
45  oth.undoAtEnd=
46  false;
47  }
48 
49  /// Create, do and set what to do at destruction
50  template <typename FBegin> // Type of the function which is called at creation
51  ScopeDoer(FBegin fBegin,
52  FEnd fEnd) :
53  fEnd(fEnd)
54  {
55  undoAtEnd=
56  fBegin();
57  }
58 
59  /// Create, set what to do at destruction
60  ScopeDoer(FEnd fEnd) :
61  fEnd(fEnd)
62  {
63  undoAtEnd=
64  true;
65  }
66 
67  /// Destroy undoing
68  ~ScopeDoer()
69  {
70  if(undoAtEnd)
71  fEnd();
72  }
73  };
74 
75  /// Set a variable for the scope, change it back at the end
76  template <typename T,
77  typename TV>
78  auto getScopeChangeVar(T& ref, ///< Reference
79  const TV& val) ///< Value to set
80  {
81  /// Old value
82  T oldVal=
83  ref;
84 
85  ref=
86  val;
87 
88  return
89  ScopeDoer([&ref,oldVal]()
90  {
91  ref=
92  oldVal;
93  });
94  }
95 }
96 
97 #endif
auto getScopeChangeVar(T &ref, const TV &val)
Set a variable for the scope, change it back at the end.
Definition: ScopeDoer.hpp:78