31 #ifndef REALTIME_TOOLS__REALTIME_BOX_BEST_EFFORT_H_
32 #define REALTIME_TOOLS__REALTIME_BOX_BEST_EFFORT_H_
34 #include <initializer_list>
39 #include <rcpputils/pointer_traits.hpp>
45 constexpr
auto is_ptr_or_smart_ptr = rcpputils::is_pointer<T>::value;
55 template <
class T,
typename mutex_type = std::mutex>
59 std::is_same_v<mutex_type, std::mutex> || std::is_same_v<mutex_type, std::recursive_mutex>);
60 static_assert(std::is_copy_constructible_v<T>,
"Passed type must be copy constructible");
63 using mutex_t = mutex_type;
70 template <
typename U = T>
72 const std::initializer_list<U> & init,
73 std::enable_if_t<std::is_constructible_v<U, std::initializer_list>>)
83 template <
typename U = T>
84 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
bool>
trySet(
const T & value)
86 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
87 if (!guard.try_lock()) {
98 bool trySet(
const std::function<
void(T &)> & func)
100 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
101 if (!guard.try_lock()) {
112 template <
typename U = T>
113 [[nodiscard]]
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>, std::optional<U>>
tryGet()
const
115 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
116 if (!guard.try_lock()) {
126 bool tryGet(
const std::function<
void(
const T &)> & func)
128 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
129 if (!guard.try_lock()) {
141 template <
typename U = T>
142 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
void>
set(
const T & value)
144 std::lock_guard<mutex_t> guard(lock_);
151 void set(
const std::function<
void(T &)> & func)
153 std::lock_guard<mutex_t> guard(lock_);
161 template <
typename U = T>
162 [[nodiscard]]
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>, U>
get()
const
164 std::lock_guard<mutex_t> guard(lock_);
171 template <
typename U = T>
172 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
void>
get(T & in)
const
174 std::lock_guard<mutex_t> guard(lock_);
183 void get(
const std::function<
void(
const T &)> & func)
185 std::lock_guard<mutex_t> guard(lock_);
193 template <
typename U = T>
194 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
void>
operator=(
const T & value)
203 template <
typename U = T,
typename =
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>>>
204 [[nodiscard]]
operator T()
const
213 template <
typename U = T,
typename =
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>>>
214 [[nodiscard]]
operator std::optional<T>()
const
223 [[nodiscard]]
const mutex_t & getMutex()
const {
return lock_; }
224 [[nodiscard]] mutex_t & getMutex() {
return lock_; }
228 mutable mutex_t lock_;