libsemigroups  v3.2.0
C++ library for semigroups and monoids
Loading...
Searching...
No Matches
guard.hpp
1//
2// libsemigroups - C++ library for semigroups and monoids
3// Copyright (C) 2025 James D. Mitchell
4//
5// This program is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// This program is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with this program. If not, see <http://www.gnu.org/licenses/>.
17//
18
19#ifndef LIBSEMIGROUPS_DETAIL_GUARD_HPP_
20#define LIBSEMIGROUPS_DETAIL_GUARD_HPP_
21
22#include "libsemigroups/is_specialization_of.hpp"
23#include <atomic> // for std::atomic
24
25namespace libsemigroups {
26 namespace detail {
27 // A simple class for ensuring that a value is set back to its value at the
28 // time of the creation of the Guard. Probably should only be used with POD
29 // types for Thing.
30 template <typename Thing>
31 class Guard {
32 Thing _old_value;
33 Thing& _value;
34
35 public:
36 Guard() = delete;
37 Guard(Guard const&) = delete;
38 Guard(Guard&&) = delete;
39 Guard& operator=(Guard const&) = delete;
40 Guard& operator=(Guard&&) = delete;
41
42 Guard(Thing& value, Thing new_value) : _old_value(value), _value(value) {
43 _value = new_value;
44 }
45
46 template <typename Value>
47 Guard(Thing& value, Value new_value)
48 : _old_value(value.load()), _value(value) {
49 _value = new_value;
50 }
51
52 explicit Guard(Thing& value) : _old_value(value), _value(value) {}
53
54 ~Guard() {
56 _value = _old_value.load();
57 } else {
58 _value = _old_value;
59 }
60 }
61 };
62
63 template <typename Thing>
64 Guard(Thing& value, typename Thing::value_type new_value) -> Guard<Thing>;
65
66 } // namespace detail
67} // namespace libsemigroups
68#endif // LIBSEMIGROUPS_DETAIL_GUARD_HPP_
constexpr bool is_specialization_of_v
Helper variable template for is_specialization_of.
Definition is_specialization_of.hpp:83
Namespace for everything in the libsemigroups library.
Definition action.hpp:44