function_ref.h 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. // Copyright 2019 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: function_ref.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file defines the `y_absl::FunctionRef` type for holding a
  20. // non-owning reference to an object of any invocable type. This function
  21. // reference is typically most useful as a type-erased argument type for
  22. // accepting function types that neither take ownership nor copy the type; using
  23. // the reference type in this case avoids a copy and an allocation. Best
  24. // practices of other non-owning reference-like objects (such as
  25. // `y_absl::string_view`) apply here.
  26. //
  27. // An `y_absl::FunctionRef` is similar in usage to a `std::function` but has the
  28. // following differences:
  29. //
  30. // * It doesn't own the underlying object.
  31. // * It doesn't have a null or empty state.
  32. // * It never performs deep copies or allocations.
  33. // * It's much faster and cheaper to construct.
  34. // * It's trivially copyable and destructable.
  35. //
  36. // Generally, `y_absl::FunctionRef` should not be used as a return value, data
  37. // member, or to initialize a `std::function`. Such usages will often lead to
  38. // problematic lifetime issues. Once you convert something to an
  39. // `y_absl::FunctionRef` you cannot make a deep copy later.
  40. //
  41. // This class is suitable for use wherever a "const std::function<>&"
  42. // would be used without making a copy. ForEach functions and other versions of
  43. // the visitor pattern are a good example of when this class should be used.
  44. //
  45. // This class is trivial to copy and should be passed by value.
  46. #ifndef Y_ABSL_FUNCTIONAL_FUNCTION_REF_H_
  47. #define Y_ABSL_FUNCTIONAL_FUNCTION_REF_H_
  48. #include <cassert>
  49. #include <functional>
  50. #include <type_traits>
  51. #include "y_absl/base/attributes.h"
  52. #include "y_absl/functional/internal/function_ref.h"
  53. #include "y_absl/meta/type_traits.h"
  54. namespace y_absl {
  55. Y_ABSL_NAMESPACE_BEGIN
  56. // FunctionRef
  57. //
  58. // Dummy class declaration to allow the partial specialization based on function
  59. // types below.
  60. template <typename T>
  61. class FunctionRef;
  62. // FunctionRef
  63. //
  64. // An `y_absl::FunctionRef` is a lightweight wrapper to any invocable object with
  65. // a compatible signature. Generally, an `y_absl::FunctionRef` should only be used
  66. // as an argument type and should be preferred as an argument over a const
  67. // reference to a `std::function`. `y_absl::FunctionRef` itself does not allocate,
  68. // although the wrapped invocable may.
  69. //
  70. // Example:
  71. //
  72. // // The following function takes a function callback by const reference
  73. // bool Visitor(const std::function<void(my_proto&,
  74. // y_absl::string_view)>& callback);
  75. //
  76. // // Assuming that the function is not stored or otherwise copied, it can be
  77. // // replaced by an `y_absl::FunctionRef`:
  78. // bool Visitor(y_absl::FunctionRef<void(my_proto&, y_absl::string_view)>
  79. // callback);
  80. //
  81. // Note: the assignment operator within an `y_absl::FunctionRef` is intentionally
  82. // deleted to prevent misuse; because the `y_absl::FunctionRef` does not own the
  83. // underlying type, assignment likely indicates misuse.
  84. template <typename R, typename... Args>
  85. class FunctionRef<R(Args...)> {
  86. private:
  87. // Used to disable constructors for objects that are not compatible with the
  88. // signature of this FunctionRef.
  89. template <typename F,
  90. typename FR = y_absl::base_internal::invoke_result_t<F, Args&&...>>
  91. using EnableIfCompatible =
  92. typename std::enable_if<std::is_void<R>::value ||
  93. std::is_convertible<FR, R>::value>::type;
  94. public:
  95. // Constructs a FunctionRef from any invocable type.
  96. template <typename F, typename = EnableIfCompatible<const F&>>
  97. // NOLINTNEXTLINE(runtime/explicit)
  98. FunctionRef(const F& f Y_ABSL_ATTRIBUTE_LIFETIME_BOUND)
  99. : invoker_(&y_absl::functional_internal::InvokeObject<F, R, Args...>) {
  100. y_absl::functional_internal::AssertNonNull(f);
  101. ptr_.obj = &f;
  102. }
  103. // Overload for function pointers. This eliminates a level of indirection that
  104. // would happen if the above overload was used (it lets us store the pointer
  105. // instead of a pointer to a pointer).
  106. //
  107. // This overload is also used for references to functions, since references to
  108. // functions can decay to function pointers implicitly.
  109. template <
  110. typename F, typename = EnableIfCompatible<F*>,
  111. y_absl::functional_internal::EnableIf<y_absl::is_function<F>::value> = 0>
  112. FunctionRef(F* f) // NOLINT(runtime/explicit)
  113. : invoker_(&y_absl::functional_internal::InvokeFunction<F*, R, Args...>) {
  114. assert(f != nullptr);
  115. ptr_.fun = reinterpret_cast<decltype(ptr_.fun)>(f);
  116. }
  117. // To help prevent subtle lifetime bugs, FunctionRef is not assignable.
  118. // Typically, it should only be used as an argument type.
  119. FunctionRef& operator=(const FunctionRef& rhs) = delete;
  120. FunctionRef(const FunctionRef& rhs) = default;
  121. // Call the underlying object.
  122. R operator()(Args... args) const {
  123. return invoker_(ptr_, std::forward<Args>(args)...);
  124. }
  125. private:
  126. y_absl::functional_internal::VoidPtr ptr_;
  127. y_absl::functional_internal::Invoker<R, Args...> invoker_;
  128. };
  129. Y_ABSL_NAMESPACE_END
  130. } // namespace y_absl
  131. #endif // Y_ABSL_FUNCTIONAL_FUNCTION_REF_H_