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