Blender  V3.3
BLI_function_ref.hh
Go to the documentation of this file.
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 
3 #pragma once
4 
5 #include <optional>
6 #include <type_traits>
7 #include <utility>
8 
9 #include "BLI_utildefines.h"
10 
69 #include "BLI_memory_utils.hh"
70 
71 namespace blender {
72 
73 template<typename Function> class FunctionRef;
74 
75 template<typename Ret, typename... Params> class FunctionRef<Ret(Params...)> {
76  private:
80  Ret (*callback_)(intptr_t callable, Params... params) = nullptr;
81 
91  intptr_t callable_;
92 
93  template<typename Callable> static Ret callback_fn(intptr_t callable, Params... params)
94  {
95  return (*reinterpret_cast<Callable *>(callable))(std::forward<Params>(params)...);
96  }
97 
98  public:
99  FunctionRef() = default;
100 
101  FunctionRef(std::nullptr_t)
102  {
103  }
104 
115  template<typename Callable,
116  BLI_ENABLE_IF((
117  !std::is_same_v<std::remove_cv_t<std::remove_reference_t<Callable>>, FunctionRef>))>
118  FunctionRef(Callable &&callable)
119  : callback_(callback_fn<typename std::remove_reference_t<Callable>>),
120  callable_(reinterpret_cast<intptr_t>(&callable))
121  {
122  }
123 
129  Ret operator()(Params... params) const
130  {
131  BLI_assert(callback_ != nullptr);
132  return callback_(callable_, std::forward<Params>(params)...);
133  }
134 
135  using OptionalReturnValue = std::conditional_t<std::is_void_v<Ret>, void, std::optional<Ret>>;
136 
143  {
144  if constexpr (std::is_void_v<Ret>) {
145  if (callback_ == nullptr) {
146  return;
147  }
148  callback_(callable_, std::forward<Params>(params)...);
149  }
150  else {
151  if (callback_ == nullptr) {
152  return {};
153  }
154  return callback_(callable_, std::forward<Params>(params)...);
155  }
156  }
157 
162  operator bool() const
163  {
164  /* Just checking `callback_` is enough to determine if the `FunctionRef` is in a state that it
165  * can be called in. */
166  return callback_ != nullptr;
167  }
168 };
169 
170 } // namespace blender
#define BLI_assert(a)
Definition: BLI_assert.h:46
#define BLI_ENABLE_IF(condition)
std::conditional_t< std::is_void_v< Ret >, void, std::optional< Ret > > OptionalReturnValue
OptionalReturnValue call_safe(Params... params) const
Ret operator()(Params... params) const
SyclQueue void void size_t num_bytes void
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
_W64 int intptr_t
Definition: stdint.h:118