any_invocable.h 13 KB

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