BRICKS
Small, useful blocks of code, to build bigger things.
Loading...
Searching...
No Matches
write_guard.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <type_traits>
4
5namespace bricks::detail {
6
7template <typename T, typename mutex_type>
8class write_guard {
9 public:
10 write_guard(T& this_in, mutex_type& mutex_in) noexcept : this_(this_in), mutex_(mutex_in)
11 {
12 mutex_.lock();
13 }
14
15 ~write_guard() noexcept { mutex_.unlock(); }
16
17 write_guard(const write_guard&) = delete;
18 auto operator=(const write_guard&) -> write_guard& = delete;
19
20 write_guard(write_guard&&) noexcept = default;
21 auto operator=(write_guard&&) noexcept -> write_guard& = default;
22
23 template <typename U = T, typename std::enable_if_t<!std::is_const_v<U>, bool> = true>
24 auto operator->() noexcept -> typename T::value_type*
25 {
26 return &this_;
27 }
28 auto operator->() const noexcept -> const typename T::value_type* { return &this_; }
29
30 template <typename U = T, typename std::enable_if_t<!std::is_const_v<U>, bool> = true>
31 auto operator*() noexcept -> typename T::value_type&
32 {
33 return this_;
34 }
35 auto operator*() const noexcept -> const typename T::value_type& { return this_; }
36
37 private:
38 T& this_;
39 mutex_type& mutex_;
40};
41
42} // namespace bricks::detail