Line data Source code
1 : /*
2 : ==============================================================================
3 : The LLVM Project is under the Apache License v2.0 with LLVM Exceptions:
4 : ==============================================================================
5 :
6 : Apache License
7 : Version 2.0, January 2004
8 : http://www.apache.org/licenses/
9 : * Copyright LLVM
10 : * https://llvm.org/doxygen/classllvm_1_1function__ref_3_01Ret_07Params_8_8_8_08_4.html
11 : */
12 :
13 : #pragma once
14 : #pragma once
15 :
16 : #include <cstdint>
17 : #include <type_traits>
18 : #include <utility>
19 :
20 : namespace spb::detail
21 : {
22 :
23 : template <typename Fn> class function_ref;
24 :
25 : template <typename Ret, typename... Params> class function_ref<Ret(Params...)>
26 : {
27 : Ret (*callback)(intptr_t callable, Params... params) = nullptr;
28 : intptr_t callable;
29 :
30 14282 : template <typename Callable> static Ret callback_fn(intptr_t callable, Params... params)
31 : {
32 51388 : return (*reinterpret_cast<Callable *>(callable))(std::forward<Params>(params)...);
33 : }
34 :
35 : public:
36 : function_ref() = default;
37 34 : function_ref(std::nullptr_t)
38 34 : {
39 34 : }
40 :
41 : template <typename Callable>
42 2566 : function_ref(
43 : Callable &&callable,
44 : // This is not the copy-constructor.
45 : std::enable_if_t<!std::is_same<std::remove_cvref_t<Callable>, function_ref>::value> * = nullptr,
46 : // Functor must be callable and return a suitable type.
47 : std::enable_if_t<std::is_void<Ret>::value ||
48 : std::is_convertible<decltype(std::declval<Callable>()(std::declval<Params>()...)),
49 : Ret>::value> * = nullptr)
50 2566 : : callback(callback_fn<std::remove_reference_t<Callable>>),
51 2566 : callable(reinterpret_cast<intptr_t>(&callable))
52 : {
53 2566 : }
54 :
55 14282 : Ret operator()(Params... params) const
56 : {
57 51388 : return callback(callable, std::forward<Params>(params)...);
58 : }
59 :
60 4696 : explicit operator bool() const
61 : {
62 4696 : return callback;
63 : }
64 : };
65 : } // namespace spb::detail
|