Blender V4.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 <optional>
8#include <type_traits>
9#include <utility>
10
11#include "BLI_utildefines.h"
12
70#include "BLI_memory_utils.hh"
71
72namespace blender {
73
74template<typename Function> class FunctionRef;
75
76template<typename Ret, typename... Params> class FunctionRef<Ret(Params...)> {
77 private:
81 Ret (*callback_)(intptr_t callable, Params... params) = nullptr;
82
92 intptr_t callable_;
93
94 template<typename Callable> static Ret callback_fn(intptr_t callable, Params... params)
95 {
96 return (*reinterpret_cast<Callable *>(callable))(std::forward<Params>(params)...);
97 }
98
99 public:
100 FunctionRef() = default;
101
102 FunctionRef(std::nullptr_t) {}
103
114 template<typename Callable,
116 !std::is_same_v<std::remove_cv_t<std::remove_reference_t<Callable>>, FunctionRef>)),
117 BLI_ENABLE_IF((std::is_invocable_r_v<Ret, Callable, Params...>))>
118 FunctionRef(Callable &&callable)
119 : callback_(callback_fn<typename std::remove_reference_t<Callable>>),
120 callable_(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
139 operator bool() const
140 {
141 /* Just checking `callback_` is enough to determine if the `FunctionRef` is in a state that it
142 * can be called in. */
143 return callback_ != nullptr;
144 }
145};
146
147} // namespace blender
#define BLI_assert(a)
Definition BLI_assert.h:50
#define BLI_ENABLE_IF(condition)
Ret operator()(Params... params) const
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
_W64 int intptr_t
Definition stdint.h:118