You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

any_invocable.h 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. // Copyright 2022 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: any_invocable.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file defines an `absl::AnyInvocable` type that assumes ownership
  20. // and wraps an object of an invocable type. (Invocable types adhere to the
  21. // concept specified in https://en.cppreference.com/w/cpp/concepts/invocable.)
  22. //
  23. // In general, prefer `absl::AnyInvocable` when you need a type-erased
  24. // function parameter that needs to take ownership of the type.
  25. //
  26. // NOTE: `absl::AnyInvocable` is similar to the C++23 `std::move_only_function`
  27. // abstraction, but has a slightly different API and is not designed to be a
  28. // drop-in replacement or C++11-compatible backfill of that type.
  29. #ifndef ABSL_FUNCTIONAL_ANY_INVOCABLE_H_
  30. #define ABSL_FUNCTIONAL_ANY_INVOCABLE_H_
  31. #include <cstddef>
  32. #include <initializer_list>
  33. #include <type_traits>
  34. #include <utility>
  35. #include "absl/base/config.h"
  36. #include "absl/functional/internal/any_invocable.h"
  37. #include "absl/meta/type_traits.h"
  38. #include "absl/utility/utility.h"
  39. namespace absl
  40. {
  41. ABSL_NAMESPACE_BEGIN
  42. // absl::AnyInvocable
  43. //
  44. // `absl::AnyInvocable` is a functional wrapper type, like `std::function`, that
  45. // assumes ownership of an invocable object. Unlike `std::function`, an
  46. // `absl::AnyInvocable` is more type-safe and provides the following additional
  47. // benefits:
  48. //
  49. // * Properly adheres to const correctness of the underlying type
  50. // * Is move-only so avoids concurrency problems with copied invocables and
  51. // unnecessary copies in general.
  52. // * Supports reference qualifiers allowing it to perform unique actions (noted
  53. // below).
  54. //
  55. // `absl::AnyInvocable` is a template, and an `absl::AnyInvocable` instantiation
  56. // may wrap any invocable object with a compatible function signature, e.g.
  57. // having arguments and return types convertible to types matching the
  58. // `absl::AnyInvocable` signature, and also matching any stated reference
  59. // qualifiers, as long as that type is moveable. It therefore provides broad
  60. // type erasure for functional objects.
  61. //
  62. // An `absl::AnyInvocable` is typically used as a type-erased function parameter
  63. // for accepting various functional objects:
  64. //
  65. // // Define a function taking an AnyInvocable parameter.
  66. // void my_func(absl::AnyInvocable<int()> f) {
  67. // ...
  68. // };
  69. //
  70. // // That function can accept any invocable type:
  71. //
  72. // // Accept a function reference. We don't need to move a reference.
  73. // int func1() { return 0; };
  74. // my_func(func1);
  75. //
  76. // // Accept a lambda. We use std::move here because otherwise my_func would
  77. // // copy the lambda.
  78. // auto lambda = []() { return 0; };
  79. // my_func(std::move(lambda));
  80. //
  81. // // Accept a function pointer. We don't need to move a function pointer.
  82. // func2 = &func1;
  83. // my_func(func2);
  84. //
  85. // // Accept an std::function by moving it. Note that the lambda is copyable
  86. // // (satisfying std::function requirements) and moveable (satisfying
  87. // // absl::AnyInvocable requirements).
  88. // std::function<int()> func6 = []() { return 0; };
  89. // my_func(std::move(func6));
  90. //
  91. // `AnyInvocable` also properly respects `const` qualifiers, reference
  92. // qualifiers, and the `noexcept` specification (only in C++ 17 and beyond) as
  93. // part of the user-specified function type (e.g.
  94. // `AnyInvocable<void()&& const noexcept>`). These qualifiers will be applied to
  95. // the `AnyInvocable` object's `operator()`, and the underlying invocable must
  96. // be compatible with those qualifiers.
  97. //
  98. // Comparison of const and non-const function types:
  99. //
  100. // // Store a closure inside of `func` with the function type `int()`.
  101. // // Note that we have made `func` itself `const`.
  102. // const AnyInvocable<int()> func = [](){ return 0; };
  103. //
  104. // func(); // Compile-error: the passed type `int()` isn't `const`.
  105. //
  106. // // Store a closure inside of `const_func` with the function type
  107. // // `int() const`.
  108. // // Note that we have also made `const_func` itself `const`.
  109. // const AnyInvocable<int() const> const_func = [](){ return 0; };
  110. //
  111. // const_func(); // Fine: `int() const` is `const`.
  112. //
  113. // In the above example, the call `func()` would have compiled if
  114. // `std::function` were used even though the types are not const compatible.
  115. // This is a bug, and using `absl::AnyInvocable` properly detects that bug.
  116. //
  117. // In addition to affecting the signature of `operator()`, the `const` and
  118. // reference qualifiers of the function type also appropriately constrain which
  119. // kinds of invocable objects you are allowed to place into the `AnyInvocable`
  120. // instance. If you specify a function type that is const-qualified, then
  121. // anything that you attempt to put into the `AnyInvocable` must be callable on
  122. // a `const` instance of that type.
  123. //
  124. // Constraint example:
  125. //
  126. // // Fine because the lambda is callable when `const`.
  127. // AnyInvocable<int() const> func = [=](){ return 0; };
  128. //
  129. // // This is a compile-error because the lambda isn't callable when `const`.
  130. // AnyInvocable<int() const> error = [=]() mutable { return 0; };
  131. //
  132. // An `&&` qualifier can be used to express that an `absl::AnyInvocable`
  133. // instance should be invoked at most once:
  134. //
  135. // // Invokes `continuation` with the logical result of an operation when
  136. // // that operation completes (common in asynchronous code).
  137. // void CallOnCompletion(AnyInvocable<void(int)&&> continuation) {
  138. // int result_of_foo = foo();
  139. //
  140. // // `std::move` is required because the `operator()` of `continuation` is
  141. // // rvalue-reference qualified.
  142. // std::move(continuation)(result_of_foo);
  143. // }
  144. //
  145. // Credits to Matt Calabrese (https://github.com/mattcalabrese) for the original
  146. // implementation.
  147. template<class Sig>
  148. class AnyInvocable : private internal_any_invocable::Impl<Sig>
  149. {
  150. private:
  151. static_assert(
  152. std::is_function<Sig>::value,
  153. "The template argument of AnyInvocable must be a function type."
  154. );
  155. using Impl = internal_any_invocable::Impl<Sig>;
  156. public:
  157. // The return type of Sig
  158. using result_type = typename Impl::result_type;
  159. // Constructors
  160. // Constructs the `AnyInvocable` in an empty state.
  161. AnyInvocable() noexcept = default;
  162. AnyInvocable(std::nullptr_t) noexcept
  163. {
  164. } // NOLINT
  165. // Constructs the `AnyInvocable` from an existing `AnyInvocable` by a move.
  166. // Note that `f` is not guaranteed to be empty after move-construction,
  167. // although it may be.
  168. AnyInvocable(AnyInvocable&& /*f*/) noexcept = default;
  169. // Constructs an `AnyInvocable` from an invocable object.
  170. //
  171. // Upon construction, `*this` is only empty if `f` is a function pointer or
  172. // member pointer type and is null, or if `f` is an `AnyInvocable` that is
  173. // empty.
  174. template<class F, typename = absl::enable_if_t<internal_any_invocable::CanConvert<Sig, F>::value>>
  175. AnyInvocable(F&& f) // NOLINT
  176. :
  177. Impl(internal_any_invocable::ConversionConstruct(), std::forward<F>(f))
  178. {
  179. }
  180. // Constructs an `AnyInvocable` that holds an invocable object of type `T`,
  181. // which is constructed in-place from the given arguments.
  182. //
  183. // Example:
  184. //
  185. // AnyInvocable<int(int)> func(
  186. // absl::in_place_type<PossiblyImmovableType>, arg1, arg2);
  187. //
  188. template<class T, class... Args, typename = absl::enable_if_t<internal_any_invocable::CanEmplace<Sig, T, Args...>::value>>
  189. explicit AnyInvocable(absl::in_place_type_t<T>, Args&&... args) :
  190. Impl(absl::in_place_type<absl::decay_t<T>>, std::forward<Args>(args)...)
  191. {
  192. static_assert(std::is_same<T, absl::decay_t<T>>::value, "The explicit template argument of in_place_type is required "
  193. "to be an unqualified object type.");
  194. }
  195. // Overload of the above constructor to support list-initialization.
  196. template<class T, class U, class... Args, typename = absl::enable_if_t<internal_any_invocable::CanEmplace<Sig, T, std::initializer_list<U>&, Args...>::value>>
  197. explicit AnyInvocable(absl::in_place_type_t<T>, std::initializer_list<U> ilist, Args&&... args) :
  198. Impl(absl::in_place_type<absl::decay_t<T>>, ilist, std::forward<Args>(args)...)
  199. {
  200. static_assert(std::is_same<T, absl::decay_t<T>>::value, "The explicit template argument of in_place_type is required "
  201. "to be an unqualified object type.");
  202. }
  203. // Assignment Operators
  204. // Assigns an `AnyInvocable` through move-assignment.
  205. // Note that `f` is not guaranteed to be empty after move-assignment
  206. // although it may be.
  207. AnyInvocable& operator=(AnyInvocable&& /*f*/) noexcept = default;
  208. // Assigns an `AnyInvocable` from a nullptr, clearing the `AnyInvocable`. If
  209. // not empty, destroys the target, putting `*this` into an empty state.
  210. AnyInvocable& operator=(std::nullptr_t) noexcept
  211. {
  212. this->Clear();
  213. return *this;
  214. }
  215. // Assigns an `AnyInvocable` from an existing `AnyInvocable` instance.
  216. //
  217. // Upon assignment, `*this` is only empty if `f` is a function pointer or
  218. // member pointer type and is null, or if `f` is an `AnyInvocable` that is
  219. // empty.
  220. template<class F, typename = absl::enable_if_t<internal_any_invocable::CanAssign<Sig, F>::value>>
  221. AnyInvocable& operator=(F&& f)
  222. {
  223. *this = AnyInvocable(std::forward<F>(f));
  224. return *this;
  225. }
  226. // Assigns an `AnyInvocable` from a reference to an invocable object.
  227. // Upon assignment, stores a reference to the invocable object in the
  228. // `AnyInvocable` instance.
  229. template<
  230. class F,
  231. typename = absl::enable_if_t<
  232. internal_any_invocable::CanAssignReferenceWrapper<Sig, F>::value>>
  233. AnyInvocable& operator=(std::reference_wrapper<F> f) noexcept
  234. {
  235. *this = AnyInvocable(f);
  236. return *this;
  237. }
  238. // Destructor
  239. // If not empty, destroys the target.
  240. ~AnyInvocable() = default;
  241. // absl::AnyInvocable::swap()
  242. //
  243. // Exchanges the targets of `*this` and `other`.
  244. void swap(AnyInvocable& other) noexcept
  245. {
  246. std::swap(*this, other);
  247. }
  248. // abl::AnyInvocable::operator bool()
  249. //
  250. // Returns `true` if `*this` is not empty.
  251. explicit operator bool() const noexcept
  252. {
  253. return this->HasValue();
  254. }
  255. // Invokes the target object of `*this`. `*this` must not be empty.
  256. //
  257. // Note: The signature of this function call operator is the same as the
  258. // template parameter `Sig`.
  259. using Impl::operator();
  260. // Equality operators
  261. // Returns `true` if `*this` is empty.
  262. friend bool operator==(const AnyInvocable& f, std::nullptr_t) noexcept
  263. {
  264. return !f.HasValue();
  265. }
  266. // Returns `true` if `*this` is empty.
  267. friend bool operator==(std::nullptr_t, const AnyInvocable& f) noexcept
  268. {
  269. return !f.HasValue();
  270. }
  271. // Returns `false` if `*this` is empty.
  272. friend bool operator!=(const AnyInvocable& f, std::nullptr_t) noexcept
  273. {
  274. return f.HasValue();
  275. }
  276. // Returns `false` if `*this` is empty.
  277. friend bool operator!=(std::nullptr_t, const AnyInvocable& f) noexcept
  278. {
  279. return f.HasValue();
  280. }
  281. // swap()
  282. //
  283. // Exchanges the targets of `f1` and `f2`.
  284. friend void swap(AnyInvocable& f1, AnyInvocable& f2) noexcept
  285. {
  286. f1.swap(f2);
  287. }
  288. private:
  289. // Friending other instantiations is necessary for conversions.
  290. template<bool /*SigIsNoexcept*/, class /*ReturnType*/, class... /*P*/>
  291. friend class internal_any_invocable::CoreImpl;
  292. };
  293. ABSL_NAMESPACE_END
  294. } // namespace absl
  295. #endif // ABSL_FUNCTIONAL_ANY_INVOCABLE_H_