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>
59 static_assert(std::is_copy_constructible_v<T>,
"Passed type must be copy constructible");
62 using mutex_t = mutex_type;
69 template <
typename U = T>
71 const std::initializer_list<U> & init,
72 std::enable_if_t<std::is_constructible_v<U, std::initializer_list<U>>>)
82 template <
typename U = T>
83 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
bool>
trySet(
const T & value)
85 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
86 if (!guard.try_lock()) {
97 bool trySet(
const std::function<
void(T &)> & func)
99 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
100 if (!guard.try_lock()) {
111 template <
typename U = T>
112 [[nodiscard]]
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>, std::optional<U>>
tryGet()
const
114 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
115 if (!guard.try_lock()) {
125 bool tryGet(
const std::function<
void(
const T &)> & func)
127 std::unique_lock<mutex_t> guard(lock_, std::defer_lock);
128 if (!guard.try_lock()) {
140 template <
typename U = T>
141 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
void>
set(
const T & value)
143 std::lock_guard<mutex_t> guard(lock_);
150 void set(
const std::function<
void(T &)> & func)
152 std::lock_guard<mutex_t> guard(lock_);
160 template <
typename U = T>
161 [[nodiscard]]
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>, U>
get()
const
163 std::lock_guard<mutex_t> guard(lock_);
170 template <
typename U = T>
171 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
void>
get(T & in)
const
173 std::lock_guard<mutex_t> guard(lock_);
182 void get(
const std::function<
void(
const T &)> & func)
184 std::lock_guard<mutex_t> guard(lock_);
192 template <
typename U = T>
193 typename std::enable_if_t<!is_ptr_or_smart_ptr<U>,
void>
operator=(
const T & value)
202 template <
typename U = T,
typename =
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>>>
203 [[nodiscard]]
operator T()
const
212 template <
typename U = T,
typename =
typename std::enable_if_t<!is_ptr_or_smart_ptr<U>>>
213 [[nodiscard]]
operator std::optional<T>()
const
222 [[nodiscard]]
const mutex_t & getMutex()
const {
return lock_; }
223 [[nodiscard]] mutex_t & getMutex() {
return lock_; }
227 mutable mutex_t lock_;