Blender V5.3
BLI_function_ref.hh
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#pragma once
6
7#include <type_traits>
8#include <utility>
9
10#include "BLI_build_config.hh"
11#include "BLI_utildefines.hh"
12
13namespace blender {
14
71
72template<typename Function> class FunctionRef;
73
74template<typename Ret, typename... Params> class FunctionRef<Ret(Params...)> {
75 private:
79 Ret (*callback_)(intptr_t callable, Params... params) = nullptr;
80
90 intptr_t callable_;
91
92 template<typename Callable> static Ret callback_fn(intptr_t callable, Params... params)
93 {
94 return (*reinterpret_cast<Callable *>(callable))(std::forward<Params>(params)...);
95 }
96
97 public:
98 FunctionRef() = default;
99
100 FunctionRef(std::nullptr_t) {}
101
112 template<typename Callable>
113 FunctionRef(Callable &&callable)
114 requires(!std::is_same_v<std::remove_cv_t<std::remove_reference_t<Callable>>, FunctionRef> &&
115 std::is_invocable_r_v<Ret, Callable, Params...>)
116 : callback_(callback_fn<typename std::remove_reference_t<Callable>>),
117 callable_(intptr_t(&callable))
118 {
119 if constexpr (std::is_constructible_v<bool, Callable>) {
120 /* For some types, the compiler can be sure that the callable is always truthy. Good!
121 * Then the entire check can be optimized away. */
122#if COMPILER_CLANG || COMPILER_GCC
123# pragma GCC diagnostic push
124# pragma GCC diagnostic ignored "-Waddress"
125# if COMPILER_GCC
126# pragma GCC diagnostic ignored "-Wnonnull-compare"
127# endif
128#endif
129 /* Make sure the #FunctionRef is falsy if the callback is falsy.
130 * That can happen when passing in null or empty std::function. */
131 const bool is_truthy = bool(callable);
132 if (!is_truthy) {
133 callback_ = nullptr;
134 callable_ = 0;
135 }
136#if COMPILER_CLANG || COMPILER_GCC
137# pragma GCC diagnostic pop
138#endif
139 }
140 }
141
147 Ret operator()(Params... params) const
148 {
149 BLI_assert(callback_ != nullptr);
150 return callback_(callable_, std::forward<Params>(params)...);
151 }
152
157 operator bool() const
158 {
159 /* Just checking `callback_` is enough to determine if the `FunctionRef` is in a state that it
160 * can be called in. */
161 return callback_ != nullptr;
162 }
163};
164
165} // namespace blender
Ret operator()(Params... params) const
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
_W64 int intptr_t
Definition BKE_text.h:119