qxLib
delegate.inl
Go to the documentation of this file.
1 /**
2 
3  @file delegate.inl
4  @author Khrapov
5  @date 7.01.2024
6  @copyright (c) Nick Khrapov, 2024. All right reserved.
7 
8 **/
9 
10 namespace qx
11 {
12 
13 namespace details
14 {
15 
16 template<class return_t, class function_t>
18 {
19 public:
20  virtual ~base_invoker() noexcept = default;
21  virtual return_t invoke(const function_t& function) noexcept = 0;
22 };
23 
24 template<class return_t, class function_t, class invoke_function_t>
25 class invoker : public base_invoker<return_t, function_t>
26 {
27 public:
28  invoker(const invoke_function_t& invoke) noexcept : m_InvokeFunction(invoke)
29  {
30  }
31 
32 private:
33  virtual return_t invoke(const function_t& function) noexcept override;
34 
35 private:
36  const invoke_function_t& m_InvokeFunction;
37 };
38 
39 template<class return_t, class function_t, class invoke_function_t>
40 inline return_t invoker<return_t, function_t, invoke_function_t>::invoke(const function_t& function) noexcept
41 {
42  return m_InvokeFunction(function);
43 }
44 
45 template<class derived_t, class return_t, class... args_t>
46 base_delegate<derived_t, return_t, args_t...>::base_delegate(base_delegate&& other) noexcept
47 {
48  *this = std::move(other);
49 }
50 
51 template<class derived_t, class return_t, class... args_t>
52 typename base_delegate<derived_t, return_t, args_t...>::base_delegate& base_delegate<derived_t, return_t, args_t...>::
53  operator=(base_delegate&& other) noexcept
54 {
55  std::swap(m_optFunctions, other.m_optFunctions);
56  std::swap(m_WeakSubscriptions, other.m_WeakSubscriptions);
57  std::swap(m_pDelegateAliveMarker, other.m_pDelegateAliveMarker);
58 
59  if (m_pDelegateAliveMarker)
60  *m_pDelegateAliveMarker = this;
61 
62  if (other.m_pDelegateAliveMarker)
63  *other.m_pDelegateAliveMarker = &other;
64 
65  return *this;
66 }
67 
68 template<class derived_t, class return_t, class... args_t>
69 template<class... creation_args_t>
70 derived_t base_delegate<derived_t, return_t, args_t...>::create_singlecast(creation_args_t... args) noexcept
71 {
72  derived_t delegate;
73  if constexpr (requires(derived_t d) { d.add_weak(args...); })
74  delegate.add_weak(args...);
75  if constexpr (requires(derived_t d) { d.add_token(args...); })
76  delegate.add_token(args...);
77  else
78  QX_STATIC_ASSERT_NO_INSTANTIATION("No overload that takes these args");
79 
80  return delegate;
81 }
82 
83 template<class derived_t, class return_t, class... args_t>
84 template<callable_c<return_t, args_t...> callable_t>
86  callable_t callable,
87  priority ePriority) noexcept
88 {
89  time_ordered_priority_key key(ePriority);
90  // SSO depends on the size of the input callable
91  add_function(key, std::move(callable));
92  return key;
93 }
94 
95 template<class derived_t, class return_t, class... args_t>
96 template<class object_t>
98  object_t& object,
99  return_t (object_t::*pMethod)(args_t...),
100  priority ePriority) noexcept
101 {
102  return add_token(
103  // 2 pointers, SOO on all compilers
104  [pMethod, &object](args_t... args)
105  {
106  return (object.*pMethod)(std::forward<args_t>(args)...);
107  },
108  ePriority);
109 }
110 
111 template<class derived_t, class return_t, class... args_t>
112 template<callable_c<return_t, args_t...> callable_t>
114  callable_t callable,
115  priority ePriority) noexcept
116 {
117  // SSO depends on the size of the input callable
118  return add_destruction_callback(time_ordered_priority_key(ePriority), function_type(std::move(callable)));
119 }
120 
121 template<class derived_t, class return_t, class... args_t>
122 template<class object_t>
124  object_t& object,
125  return_t (object_t::*pMethod)(args_t...),
126  priority ePriority) noexcept
127 {
128  return add_destruction_callback(
129  time_ordered_priority_key(ePriority),
130  // 2 pointers, SOO on all compilers
131  [&object, pMethod](args_t... args)
132  {
133  return (object.*pMethod)(std::forward<args_t>(args)...);
134  });
135 }
136 
137 template<class derived_t, class return_t, class... args_t>
138 template<class object_t, callable_c<return_t, args_t...> callable_t>
140  std::weak_ptr<object_t> pWeakObject,
141  callable_t callable,
142  priority ePriority) noexcept
143 {
144  time_ordered_priority_key key(ePriority);
145  add_weak(
146  key,
147  std::move(pWeakObject),
148  // SSO depends on the size of the input callable
149  [callable_ = std::move(callable)](object_t*, args_t... args)
150  {
151  return callable_(std::forward<args_t>(args)...);
152  });
153  return key;
154 }
155 
156 template<class derived_t, class return_t, class... args_t>
157 template<class object_t>
159  std::weak_ptr<object_t> pWeakObject,
160  return_t (object_t::*pMethod)(args_t...),
161  priority ePriority) noexcept
162 {
163  time_ordered_priority_key key(ePriority);
164  add_weak(
165  key,
166  std::move(pWeakObject),
167  // 1 pointer, SOO on all compilers
168  [pMethod](object_t* pObject, args_t... args)
169  {
170  return (pObject->*pMethod)(std::forward<args_t>(args)...);
171  });
172  return key;
173 }
174 
175 template<class derived_t, class return_t, class... args_t>
177 {
178  m_WeakSubscriptions.erase(token);
179  return remove_function(token);
180 }
181 
182 template<class derived_t, class return_t, class... args_t>
184 {
185  return m_optFunctions
186  && std::visit(
187  [this, token]<class T>(T& value)
188  {
189  if constexpr (std::is_same_v<T, single_value_type>)
190  {
191  if (value.first == token)
192  {
193  m_optFunctions.reset();
194  return true;
195  }
196  else
197  {
198  return false;
199  }
200  }
201  else if constexpr (std::is_same_v<T, container_type>)
202  {
203  return value.erase(token) == 1;
204  }
205  else
206  {
207  QX_STATIC_ASSERT_NO_INSTANTIATION("Invalid type");
208  return false;
209  }
210  },
211  *m_optFunctions);
212 }
213 
214 template<class derived_t, class return_t, class... args_t>
216 {
217  m_optFunctions.reset();
218  m_WeakSubscriptions.clear();
219 }
220 
221 template<class derived_t, class return_t, class... args_t>
223 {
224  for (auto it = m_WeakSubscriptions.begin(); it != m_WeakSubscriptions.end();)
225  {
226  if (it->second.expired())
227  {
228  const delegate_token_type token = it->first;
229  it = m_WeakSubscriptions.erase(it);
230  remove_function(token);
231  }
232  else
233  {
234  ++it;
235  }
236  }
237 }
238 
239 template<class derived_t, class return_t, class... args_t>
241 {
242  if (!m_optFunctions)
243  return 0;
244 
245  return std::visit(
246  []<class T>(const T& value) -> size_t
247  {
248  if constexpr (std::is_same_v<T, single_value_type>)
249  {
250  return 1;
251  }
252  else if constexpr (std::is_same_v<T, container_type>)
253  {
254  return value.size();
255  }
256  else
257  {
258  QX_STATIC_ASSERT_NO_INSTANTIATION("Invalid type");
259  return 0;
260  }
261  },
262  *m_optFunctions);
263 }
264 
265 template<class derived_t, class return_t, class... args_t>
267 {
268  return size() == 1;
269 }
270 
271 template<class derived_t, class return_t, class... args_t>
273 {
274  return size() == 0;
275 }
276 
277 template<class derived_t, class return_t, class... args_t>
278 template<class invoke_single_t, class invoke_multiple_t>
280  const invoke_single_t& invokeSingle,
281  const invoke_multiple_t& invokeMultiple) noexcept
282 {
283  clear_dead();
284  if (!m_optFunctions)
285  {
286  if constexpr (std::is_void_v<return_t>)
287  return;
288  else
289  return return_t {};
290  }
291 
292 #if (QX_CLANG || QX_APPLE_CLANG) && QX_LIBCPP
293  // Work around recursive constraint evaluation in Bloomberg clang/libc++ when delegate arguments include
294  // std::expected: copying the map or comparing its iterators can trigger an invalid operator== lookup.
295 
296  // modifying during iteration protection
297  thread_local variant_type tempFunctions;
298  if (std::holds_alternative<single_value_type>(*m_optFunctions))
299  {
300  tempFunctions.template emplace<single_value_type>(std::get<single_value_type>(*m_optFunctions));
301  return invokeSingle(std::get<single_value_type>(tempFunctions).second);
302  }
303  else
304  {
305  const container_type& source = std::get<container_type>(*m_optFunctions);
306  if (!std::holds_alternative<container_type>(tempFunctions))
307  tempFunctions.template emplace<container_type>();
308  container_type& container = std::get<container_type>(tempFunctions);
309  bool sameKeys = source.size() == container.size();
310  if (sameKeys)
311  {
312  auto sourceIt = source.begin();
313  auto targetIt = container.begin();
314  for (size_t i = 0; i < source.size(); ++i, ++sourceIt, ++targetIt)
315  if (!(sourceIt->first == targetIt->first))
316  {
317  sameKeys = false;
318  break;
319  }
320  }
321 
322  auto sourceIt = source.begin();
323  if (sameKeys)
324  {
325  auto targetIt = container.begin();
326  for (size_t i = 0; i < source.size(); ++i, ++sourceIt, ++targetIt)
327  targetIt->second = sourceIt->second;
328  }
329  else
330  {
331  container.clear();
332  for (size_t i = 0; i < source.size(); ++i, ++sourceIt)
333  container.try_emplace(sourceIt->first, sourceIt->second);
334  }
335 
336  invoker<return_t, function_type, invoke_single_t> invokerSingle(invokeSingle);
337  invoker<return_t, function_type, invoke_multiple_t> invokerMultiple(invokeMultiple);
339  if (container.size() == 1)
340  invoker = &invokerSingle;
341  else
342  invoker = &invokerMultiple;
343  if constexpr (std::is_void_v<return_t>)
344  {
345  size_t index = 0;
346  for (auto it = container.begin(); index < container.size(); ++it, ++index)
347  invoker->invoke(it->second);
348 
349  return;
350  }
351  else if constexpr (delegate_pipe_c<return_t>)
352  {
353  return_t result {};
354  size_t index = 0;
355  for (auto it = container.begin(); index < container.size(); ++it, ++index)
356  result = result | invoker->invoke(it->second);
357 
358  return result;
359  }
360  else
361  {
362  return_t result {};
363  size_t index = 0;
364  for (auto it = container.begin(); index < container.size(); ++it, ++index)
365  result = invoker->invoke(it->second);
366 
367  return result;
368  }
369  }
370 #else
371  // modifying during iteration protection
372  thread_local variant_type tempFunctions;
373  tempFunctions = *m_optFunctions;
374 
375  if (std::holds_alternative<single_value_type>(tempFunctions))
376  {
377  const auto& [_, function] = std::get<single_value_type>(tempFunctions);
378  return invokeSingle(function);
379  }
380  else
381  {
382  const container_type& container = std::get<container_type>(tempFunctions);
383 
384  invoker<return_t, function_type, invoke_single_t> invokerSingle(invokeSingle);
385  invoker<return_t, function_type, invoke_multiple_t> invokerMultiple(invokeMultiple);
387  if (container.size() == 1)
388  invoker = &invokerSingle;
389  else
390  invoker = &invokerMultiple;
391 
392  if constexpr (std::is_void_v<return_t>)
393  {
394  for (const auto& [_, function] : container)
395  invoker->invoke(function);
396 
397  return;
398  }
399  else if constexpr (delegate_pipe_c<return_t>)
400  {
401  return_t result {};
402  for (const auto& [_, function] : container)
403  result = result | invoker->invoke(function);
404 
405  return result;
406  }
407  else
408  {
409  return_t result {};
410  for (const auto& [_, function] : container)
411  result = invoker->invoke(function);
412 
413  return result;
414  }
415  }
416 #endif
417 }
418 
419 template<class derived_t, class return_t, class... args_t>
420 template<class object_t, callable_c<return_t, object_t*, args_t...> callable_t>
423  std::weak_ptr<object_t> pWeakObject,
424  callable_t callable) noexcept
425 {
426  m_WeakSubscriptions.emplace(key, pWeakObject);
427  add_function(
428  key,
429  [pWeakObject, callable_ = std::move(callable)](args_t... args)
430  {
431  if (std::shared_ptr<object_t> pObject = pWeakObject.lock())
432  return callable_(pObject.get(), std::forward<args_t>(args)...);
433 
434  return return_t();
435  });
436 }
437 
438 template<class derived_t, class return_t, class... args_t>
441  function_type value) noexcept
442 {
443  add_function(key, std::move(value));
444 
445  if (!m_pDelegateAliveMarker)
446  m_pDelegateAliveMarker = std::make_shared<base_delegate*>(this);
447 
448  return [key, pDelegateAliveMarker = std::weak_ptr(m_pDelegateAliveMarker)]()
449  {
450  if (const auto pDelegate = pDelegateAliveMarker.lock())
451  (*pDelegate)->remove(key);
452  };
453 }
454 
455 template<class derived_t, class return_t, class... args_t>
456 void base_delegate<derived_t, return_t, args_t...>::add_function(
457  time_ordered_priority_key key,
458  function_type function) noexcept
459 {
460  if (!m_optFunctions)
461  {
462  m_optFunctions = variant_type(single_value_type(key, std::move(function)));
463  }
464  else if (std::holds_alternative<single_value_type>(*m_optFunctions))
465  {
466  single_value_type first = std::get<single_value_type>(std::move(*m_optFunctions));
467  container_type container;
468  container.try_emplace(first.first, std::move(first.second));
469  container.try_emplace(key, std::move(function));
470  m_optFunctions = std::move(container);
471  }
472  else
473  {
474  std::get<container_type>(*m_optFunctions).try_emplace(key, std::move(function));
475  }
476 }
477 
478 } // namespace details
479 
480 template<class return_t, class... args_t>
481  requires(sizeof...(args_t) > 0 && (!std::is_void_v<args_t> && ...))
482 return_t delegate<return_t(args_t...)>::execute(args_t... args) noexcept
483 {
484  return this->execute_internal(
485  [&args...](const typename super_type::function_type& function)
486  {
487  return function(std::forward<args_t>(args)...);
488  },
489  [&args...](const typename super_type::function_type& function)
490  {
491  return function(args...);
492  });
493 }
494 
495 template<class return_t>
496 return_t delegate<return_t(void)>::execute() noexcept
497 {
498  return this->execute_internal(
499  [](const typename super_type::function_type& function)
500  {
501  return function();
502  },
503  [](const typename super_type::function_type& function)
504  {
505  return function();
506  });
507 }
508 
509 } // namespace qx
Single or multicast delegate.
Definition: delegate.h:66
Class for RAII: functor passed in constructor will be called in destructor.
Base delegate type.
Definition: delegate.h:84
void clear_dead() noexcept
Remove weak subscriptions whose tracked objects have expired, without invoking callbacks.
Definition: delegate.inl:222
delegate_token_type add_weak(std::weak_ptr< object_t > pWeakObject, callable_t callable, priority ePriority=priority::normal) noexcept
Add a callable that will be executed only if the appropriate weak object is valid.
Definition: delegate.inl:139
void clear() noexcept
Clear all the callables in this delegate.
Definition: delegate.inl:215
destruction_callback add_destruction_callback(callable_t callable, priority ePriority=priority::normal) noexcept
Add a callable that will be removed from the delegate when its destruction callback is destroyed.
Definition: delegate.inl:113
bool empty() const noexcept
Check if this delegate is empty.
Definition: delegate.inl:272
size_t size() const noexcept
Get the number of functions bound to this delegate.
Definition: delegate.inl:240
static derived_t create_singlecast(creation_args_t... args) noexcept
Create a singlecast delegate.
Definition: delegate.inl:70
bool remove(delegate_token_type token) noexcept
Remove a callable using its token.
Definition: delegate.inl:176
delegate_token_type add_token(callable_t callable, priority ePriority=priority::normal) noexcept
Add a callable using a token with manual unsubscribing.
Definition: delegate.inl:85
return_t execute_internal(const invoke_single_t &invokeSingle, const invoke_multiple_t &invokeMultiple) noexcept
Execute all callables.
Definition: delegate.inl:279
bool is_singlecast() const noexcept
Check whether exactly one callable is bound to this delegate.
Definition: delegate.inl:266
A class that can be used as a key in ordered containers so that items are ordered in descending order...
Definition: priority.h:50
requires(same_variadic_args_v< args_t... >) const expr auto coalesce(args_t &&... args)
Coalesce function, C# a ?? b analogue.
Definition: coalesce.inl:57
priority
User may use the predefined values or the custom ones, for ex. "normal - 1", this type is supposed to...
Definition: priority.h:30
#define QX_STATIC_ASSERT_NO_INSTANTIATION(Message)
This static assert will fail if block it placed in must not be instantiated.