1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
9 #include "opentelemetry/version.h"
11 OPENTELEMETRY_BEGIN_NAMESPACE
18 * Non-owning function reference that can be used as a more performant
19 * replacement for std::function when ownership sematics aren't needed.
21 * See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0792r0.html
23 * Based off of https://stackoverflow.com/a/39087660/4447365
25 template <class R
, class... Args
>
26 class function_ref
<R(Args
...)>
28 void *callable_
= nullptr;
29 R (*invoker_
)(void *, Args
...) = nullptr;
32 using FunctionPointer
= decltype(std::addressof(std::declval
<F
&>()));
35 void BindTo(F
&f
) noexcept
37 callable_
= static_cast<void *>(std::addressof(f
));
38 invoker_
= [](void *callable_
, Args
... args
) -> R
{
39 return (*static_cast<FunctionPointer
<F
>>(callable_
))(std::forward
<Args
>(args
)...);
43 template <class R_in
, class... Args_in
>
44 void BindTo(R_in (*f
)(Args_in
...)) noexcept
46 using F
= decltype(f
);
49 return BindTo(nullptr);
51 callable_
= reinterpret_cast<void *>(f
);
52 invoker_
= [](void *callable_
, Args
... args
) -> R
{
53 return (F(callable_
))(std::forward
<Args
>(args
)...);
57 void BindTo(std::nullptr_t
) noexcept
66 typename
std::enable_if
<!std::is_same
<function_ref
, typename
std::decay
<F
>::type
>::value
,
68 typename
std::enable_if
<
69 #if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && (_MSVC_LANG > 201402))
70 // std::result_of deprecated in C++17, removed in C++20
71 std::is_convertible
<typename
std::invoke_result
<F
, Args
...>::type
, R
>::value
,
73 // std::result_of since C++11
74 std::is_convertible
<typename
std::result_of
<F
&(Args
...)>::type
, R
>::value
,
79 BindTo(f
); // not forward
82 function_ref(std::nullptr_t
) {}
84 function_ref(const function_ref
&) noexcept
= default;
85 function_ref(function_ref
&&) noexcept
= default;
87 R
operator()(Args
... args
) const { return invoker_(callable_
, std::forward
<Args
>(args
)...); }
89 explicit operator bool() const { return invoker_
; }
92 OPENTELEMETRY_END_NAMESPACE