31#ifndef REALTIME_TOOLS__REALTIME_BOX_BEST_EFFORT_HPP_
32#define REALTIME_TOOLS__REALTIME_BOX_BEST_EFFORT_HPP_
35#include <initializer_list>
40#include <rcpputils/pointer_traits.hpp>
46constexpr auto is_ptr_or_smart_ptr = rcpputils::is_pointer<T>::value;
56template <
class T,
typename mutex_type = std::mutex>
60 std::is_same_v<mutex_type, std::mutex> || std::is_same_v<mutex_type, std::recursive_mutex>);
61 static_assert(std::is_copy_constructible_v<T>,
"Passed type must be copy constructible");
64 using mutex_t = mutex_type;
71 template <
typename U = T>
73 const std::initializer_list<U> & init,
74 std::enable_if_t<std::is_constructible_v<U, std::initializer_list<U>>>)
84 template <
typename U = T>
85 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
bool>
trySet(
const T & value)
87 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
88 if (!guard.try_lock()) {
99 bool trySet(
const std::function<
void(T &)> & func)
101 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
102 if (!guard.try_lock()) {
113 template <
typename U = T>
114 [[nodiscard]]
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>, std::optional<U>>
tryGet()
const
116 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
117 if (!guard.try_lock()) {
127 bool tryGet(
const std::function<
void(
const T &)> & func)
129 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
130 if (!guard.try_lock()) {
142 template <
typename U = T>
143 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
void>
set(
const T & value)
145 std::lock_guard<mutex_t> guard(lock_);
152 void set(
const std::function<
void(T &)> & func)
154 std::lock_guard<mutex_t> guard(lock_);
162 template <
typename U = T>
163 [[nodiscard]]
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>, U>
get()
const
165 std::lock_guard<mutex_t> guard(lock_);
172 template <
typename U = T>
173 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
void>
get(T & in)
const
175 std::lock_guard<mutex_t> guard(lock_);
184 void get(
const std::function<
void(
const T &)> & func)
186 std::lock_guard<mutex_t> guard(lock_);
194 template <
typename U = T>
195 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
void>
operator=(
const T & value)
204 template <
typename U = T,
typename =
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>>>
205 [[nodiscard]]
operator T()
const
214 template <
typename U = T,
typename =
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>>>
215 [[nodiscard]]
operator std::optional<T>()
const
224 [[nodiscard]]
const mutex_t & getMutex()
const {
return lock_; }
225 [[nodiscard]] mutex_t & getMutex() {
return lock_; }
229 mutable mutex_t lock_;