1 //===-- Self contained functional header ------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_LIBC_SRC_SUPPORT_CPP_FUNCTIONAL_H
10 #define LLVM_LIBC_SRC_SUPPORT_CPP_FUNCTIONAL_H
12 #include "src/__support/CPP/type_traits.h"
13 #include "src/__support/CPP/utility.h"
14 #include "src/__support/macros/attributes.h"
18 namespace __llvm_libc
{
21 /// A function type adapted from LLVM's function_ref.
22 /// This class does not own the callable, so it is not in general safe to
24 template <typename Fn
> class function
;
26 template <typename Ret
, typename
... Params
> class function
<Ret(Params
...)> {
27 Ret (*callback
)(intptr_t callable
, Params
... params
) = nullptr;
30 template <typename Callable
>
31 LIBC_INLINE
static Ret
callback_fn(intptr_t callable
, Params
... params
) {
32 return (*reinterpret_cast<Callable
*>(callable
))(
33 forward
<Params
>(params
)...);
37 LIBC_INLINE
function() = default;
38 LIBC_INLINE
function(decltype(nullptr)) {}
39 LIBC_INLINE
~function() = default;
41 template <typename Callable
>
44 // This is not the copy-constructor.
45 enable_if_t
<!is_same
<remove_cvref_t
<Callable
>, function
>::value
> * =
47 // Functor must be callable and return a suitable type.
48 enable_if_t
<is_void_v
<Ret
> ||
50 decltype(declval
<Callable
>()(declval
<Params
>()...)), Ret
>>
52 : callback(callback_fn
<remove_reference_t
<Callable
>>),
53 callable(reinterpret_cast<intptr_t>(&callable
)) {}
55 LIBC_INLINE Ret
operator()(Params
... params
) const {
56 return callback(callable
, forward
<Params
>(params
)...);
59 LIBC_INLINE
explicit operator bool() const { return callback
; }
63 } // namespace __llvm_libc
65 #endif // LLVM_LIBC_SRC_SUPPORT_CPP_FUNCTIONAL_H