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


grpc
Author(s):
autogenerated on Thu Mar 13 2025 02:58:30