FE 0.13.1
Header-only C++ frontend library
Loading...
Searching...
No Matches
restore.h
Go to the documentation of this file.
1#pragma once
2
3#include <utility>
4
5namespace fe {
6
7/// RAII guard that restores a value at the end of the scope.
8/// This primary template guards whatever @p Get reads and @p Set writes; see fe::term::ScopedMode.
9template<class T, auto Get = nullptr, auto Set = nullptr>
10class Restore {
11public:
12 /// Saves what @p Get yields and restores it in the destructor.
14 : prev_(Get()) {}
15
16 /// As above but @p Set%s @p value up front.
17 explicit Restore(T value)
18 : prev_(Get()) {
19 Set(std::move(value));
20 }
21
22 ~Restore() { Set(std::move(prev_)); }
23
24 Restore(const Restore&) = delete;
25 Restore& operator=(const Restore&) = delete;
26
27private:
28 T prev_;
29};
30
31/// Restores @p ref to its current value at the end of the scope.
32/// The two-argument constructor additionally sets @p ref to @p value up front (like `std::exchange`).
33template<class T>
34class Restore<T, nullptr, nullptr> {
35public:
36 /// Saves @p ref and restores it in the destructor.
37 explicit Restore(T& ref)
38 : ref_(ref)
39 , prev_(ref) {}
40
41 /// Saves @p ref, sets it to @p value, and restores the saved value in the destructor.
42 Restore(T& ref, T value)
43 : ref_(ref)
44 , prev_(std::exchange(ref, std::move(value))) {}
45
46 ~Restore() { ref_ = std::move(prev_); }
47
48 Restore(const Restore&) = delete;
49 Restore& operator=(const Restore&) = delete;
50
51private:
52 T& ref_;
53 T prev_;
54};
55
56/// The primary template has no two-argument constructor to deduce this one from.
57template<class T>
59
60} // namespace fe
Restore(const Restore &)=delete
Restore & operator=(const Restore &)=delete
Restore(T &ref)
Saves ref and restores it in the destructor.
Definition restore.h:37
Restore(T &ref, T value)
Saves ref, sets it to value, and restores the saved value in the destructor.
Definition restore.h:42
RAII guard that restores a value at the end of the scope.
Definition restore.h:10
Restore(T value)
As above but Sets value up front.
Definition restore.h:17
Restore & operator=(const Restore &)=delete
Restore(const Restore &)=delete
Restore()
Saves what Get yields and restores it in the destructor.
Definition restore.h:13
Definition algo.h:17
Definition span.h:129