]> git.proxmox.com Git - ceph.git/blob - ceph/src/jaegertracing/opentelemetry-cpp/api/include/opentelemetry/nostd/function_ref.h
update ceph source to reef 18.1.2
[ceph.git] / ceph / src / jaegertracing / opentelemetry-cpp / api / include / opentelemetry / nostd / function_ref.h
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 #pragma once
5
6 #include <memory>
7 #include <type_traits>
8
9 #include "opentelemetry/version.h"
10
11 OPENTELEMETRY_BEGIN_NAMESPACE
12 namespace nostd
13 {
14 template <class Sig>
15 class function_ref;
16
17 /**
18 * Non-owning function reference that can be used as a more performant
19 * replacement for std::function when ownership sematics aren't needed.
20 *
21 * See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0792r0.html
22 *
23 * Based off of https://stackoverflow.com/a/39087660/4447365
24 */
25 template <class R, class... Args>
26 class function_ref<R(Args...)>
27 {
28 void *callable_ = nullptr;
29 R (*invoker_)(void *, Args...) = nullptr;
30
31 template <class F>
32 using FunctionPointer = decltype(std::addressof(std::declval<F &>()));
33
34 template <class F>
35 void BindTo(F &f) noexcept
36 {
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)...);
40 };
41 }
42
43 template <class R_in, class... Args_in>
44 void BindTo(R_in (*f)(Args_in...)) noexcept
45 {
46 using F = decltype(f);
47 if (f == nullptr)
48 {
49 return BindTo(nullptr);
50 }
51 callable_ = reinterpret_cast<void *>(f);
52 invoker_ = [](void *callable_, Args... args) -> R {
53 return (F(callable_))(std::forward<Args>(args)...);
54 };
55 }
56
57 void BindTo(std::nullptr_t) noexcept
58 {
59 callable_ = nullptr;
60 invoker_ = nullptr;
61 }
62
63 public:
64 template <
65 class F,
66 typename std::enable_if<!std::is_same<function_ref, typename std::decay<F>::type>::value,
67 int>::type = 0,
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,
72 #else
73 // std::result_of since C++11
74 std::is_convertible<typename std::result_of<F &(Args...)>::type, R>::value,
75 #endif
76 int>::type = 0>
77 function_ref(F &&f)
78 {
79 BindTo(f); // not forward
80 }
81
82 function_ref(std::nullptr_t) {}
83
84 function_ref(const function_ref &) noexcept = default;
85 function_ref(function_ref &&) noexcept = default;
86
87 R operator()(Args... args) const { return invoker_(callable_, std::forward<Args>(args)...); }
88
89 explicit operator bool() const { return invoker_; }
90 };
91 } // namespace nostd
92 OPENTELEMETRY_END_NAMESPACE