Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-07-12 08:06:39

0001 // Copyright 2022 The Abseil Authors.
0002 //
0003 // Licensed under the Apache License, Version 2.0 (the "License");
0004 // you may not use this file except in compliance with the License.
0005 // You may obtain a copy of the License at
0006 //
0007 //      https://www.apache.org/licenses/LICENSE-2.0
0008 //
0009 // Unless required by applicable law or agreed to in writing, software
0010 // distributed under the License is distributed on an "AS IS" BASIS,
0011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0012 // See the License for the specific language governing permissions and
0013 // limitations under the License.
0014 //
0015 // -----------------------------------------------------------------------------
0016 // File: any_invocable.h
0017 // -----------------------------------------------------------------------------
0018 //
0019 // This header file defines an `absl::AnyInvocable` type that assumes ownership
0020 // and wraps an object of an invocable type. (Invocable types adhere to the
0021 // concept specified in https://en.cppreference.com/w/cpp/concepts/invocable.)
0022 //
0023 // In general, prefer `absl::AnyInvocable` when you need a type-erased
0024 // function parameter that needs to take ownership of the type.
0025 //
0026 // NOTE: `absl::AnyInvocable` is similar to the C++23 `std::move_only_function`
0027 // abstraction, but has a slightly different API and is not designed to be a
0028 // drop-in replacement or C++11-compatible backfill of that type.
0029 //
0030 // Credits to Matt Calabrese (https://github.com/mattcalabrese) for the original
0031 // implementation.
0032 
0033 #ifndef ABSL_FUNCTIONAL_ANY_INVOCABLE_H_
0034 #define ABSL_FUNCTIONAL_ANY_INVOCABLE_H_
0035 
0036 #include <cstddef>
0037 #include <functional>
0038 #include <initializer_list>
0039 #include <type_traits>
0040 #include <utility>
0041 
0042 #include "absl/base/config.h"
0043 #include "absl/functional/internal/any_invocable.h"
0044 #include "absl/meta/type_traits.h"
0045 #include "absl/utility/utility.h"
0046 
0047 namespace absl {
0048 ABSL_NAMESPACE_BEGIN
0049 
0050 // absl::AnyInvocable
0051 //
0052 // `absl::AnyInvocable` is a functional wrapper type, like `std::function`, that
0053 // assumes ownership of an invocable object. Unlike `std::function`, an
0054 // `absl::AnyInvocable` is more type-safe and provides the following additional
0055 // benefits:
0056 //
0057 // * Properly adheres to const correctness of the underlying type
0058 // * Is move-only so avoids concurrency problems with copied invocables and
0059 //   unnecessary copies in general.
0060 // * Supports reference qualifiers allowing it to perform unique actions (noted
0061 //   below).
0062 //
0063 // `absl::AnyInvocable` is a template, and an `absl::AnyInvocable` instantiation
0064 // may wrap any invocable object with a compatible function signature, e.g.
0065 // having arguments and return types convertible to types matching the
0066 // `absl::AnyInvocable` signature, and also matching any stated reference
0067 // qualifiers, as long as that type is moveable. It therefore provides broad
0068 // type erasure for functional objects.
0069 //
0070 // An `absl::AnyInvocable` is typically used as a type-erased function parameter
0071 // for accepting various functional objects:
0072 //
0073 // // Define a function taking an AnyInvocable parameter.
0074 // void my_func(absl::AnyInvocable<int()> f) {
0075 //   ...
0076 // };
0077 //
0078 // // That function can accept any invocable type:
0079 //
0080 // // Accept a function reference. We don't need to move a reference.
0081 // int func1() { return 0; };
0082 // my_func(func1);
0083 //
0084 // // Accept a lambda. We use std::move here because otherwise my_func would
0085 // // copy the lambda.
0086 // auto lambda = []() { return 0; };
0087 // my_func(std::move(lambda));
0088 //
0089 // // Accept a function pointer. We don't need to move a function pointer.
0090 // func2 = &func1;
0091 // my_func(func2);
0092 //
0093 // // Accept an std::function by moving it. Note that the lambda is copyable
0094 // // (satisfying std::function requirements) and moveable (satisfying
0095 // // absl::AnyInvocable requirements).
0096 // std::function<int()> func6 = []() { return 0; };
0097 // my_func(std::move(func6));
0098 //
0099 // `AnyInvocable` also properly respects `const` qualifiers, reference
0100 // qualifiers, and the `noexcept` specification (only in C++ 17 and beyond) as
0101 // part of the user-specified function type (e.g.
0102 // `AnyInvocable<void() const && noexcept>`). These qualifiers will be applied
0103 // to the `AnyInvocable` object's `operator()`, and the underlying invocable
0104 // must be compatible with those qualifiers.
0105 //
0106 // Comparison of const and non-const function types:
0107 //
0108 //   // Store a closure inside of `func` with the function type `int()`.
0109 //   // Note that we have made `func` itself `const`.
0110 //   const AnyInvocable<int()> func = [](){ return 0; };
0111 //
0112 //   func();  // Compile-error: the passed type `int()` isn't `const`.
0113 //
0114 //   // Store a closure inside of `const_func` with the function type
0115 //   // `int() const`.
0116 //   // Note that we have also made `const_func` itself `const`.
0117 //   const AnyInvocable<int() const> const_func = [](){ return 0; };
0118 //
0119 //   const_func();  // Fine: `int() const` is `const`.
0120 //
0121 // In the above example, the call `func()` would have compiled if
0122 // `std::function` were used even though the types are not const compatible.
0123 // This is a bug, and using `absl::AnyInvocable` properly detects that bug.
0124 //
0125 // In addition to affecting the signature of `operator()`, the `const` and
0126 // reference qualifiers of the function type also appropriately constrain which
0127 // kinds of invocable objects you are allowed to place into the `AnyInvocable`
0128 // instance. If you specify a function type that is const-qualified, then
0129 // anything that you attempt to put into the `AnyInvocable` must be callable on
0130 // a `const` instance of that type.
0131 //
0132 // Constraint example:
0133 //
0134 //   // Fine because the lambda is callable when `const`.
0135 //   AnyInvocable<int() const> func = [=](){ return 0; };
0136 //
0137 //   // This is a compile-error because the lambda isn't callable when `const`.
0138 //   AnyInvocable<int() const> error = [=]() mutable { return 0; };
0139 //
0140 // An `&&` qualifier can be used to express that an `absl::AnyInvocable`
0141 // instance should be invoked at most once:
0142 //
0143 //   // Invokes `continuation` with the logical result of an operation when
0144 //   // that operation completes (common in asynchronous code).
0145 //   void CallOnCompletion(AnyInvocable<void(int)&&> continuation) {
0146 //     int result_of_foo = foo();
0147 //
0148 //     // `std::move` is required because the `operator()` of `continuation` is
0149 //     // rvalue-reference qualified.
0150 //     std::move(continuation)(result_of_foo);
0151 //   }
0152 //
0153 // Attempting to call `absl::AnyInvocable` multiple times in such a case
0154 // results in undefined behavior.
0155 //
0156 // Invoking an empty `absl::AnyInvocable` results in undefined behavior:
0157 //
0158 //   // Create an empty instance using the default constructor.
0159 //   AnyInvocable<void()> empty;
0160 //   empty();  // WARNING: Undefined behavior!
0161 template <class Sig>
0162 class AnyInvocable : private internal_any_invocable::Impl<Sig> {
0163  private:
0164   static_assert(
0165       std::is_function<Sig>::value,
0166       "The template argument of AnyInvocable must be a function type.");
0167 
0168   using Impl = internal_any_invocable::Impl<Sig>;
0169 
0170  public:
0171   // The return type of Sig
0172   using result_type = typename Impl::result_type;
0173 
0174   // Constructors
0175 
0176   // Constructs the `AnyInvocable` in an empty state.
0177   // Invoking it results in undefined behavior.
0178   AnyInvocable() noexcept = default;
0179   AnyInvocable(std::nullptr_t) noexcept {}  // NOLINT
0180 
0181   // Constructs the `AnyInvocable` from an existing `AnyInvocable` by a move.
0182   // Note that `f` is not guaranteed to be empty after move-construction,
0183   // although it may be.
0184   AnyInvocable(AnyInvocable&& /*f*/) noexcept = default;
0185 
0186   // Constructs an `AnyInvocable` from an invocable object.
0187   //
0188   // Upon construction, `*this` is only empty if `f` is a function pointer or
0189   // member pointer type and is null, or if `f` is an `AnyInvocable` that is
0190   // empty.
0191   template <class F, typename = absl::enable_if_t<
0192                          internal_any_invocable::CanConvert<Sig, F>::value>>
0193   AnyInvocable(F&& f)  // NOLINT
0194       : Impl(internal_any_invocable::ConversionConstruct(),
0195              std::forward<F>(f)) {}
0196 
0197   // Constructs an `AnyInvocable` that holds an invocable object of type `T`,
0198   // which is constructed in-place from the given arguments.
0199   //
0200   // Example:
0201   //
0202   //   AnyInvocable<int(int)> func(
0203   //       absl::in_place_type<PossiblyImmovableType>, arg1, arg2);
0204   //
0205   template <class T, class... Args,
0206             typename = absl::enable_if_t<
0207                 internal_any_invocable::CanEmplace<Sig, T, Args...>::value>>
0208   explicit AnyInvocable(absl::in_place_type_t<T>, Args&&... args)
0209       : Impl(absl::in_place_type<absl::decay_t<T>>,
0210              std::forward<Args>(args)...) {
0211     static_assert(std::is_same<T, absl::decay_t<T>>::value,
0212                   "The explicit template argument of in_place_type is required "
0213                   "to be an unqualified object type.");
0214   }
0215 
0216   // Overload of the above constructor to support list-initialization.
0217   template <class T, class U, class... Args,
0218             typename = absl::enable_if_t<internal_any_invocable::CanEmplace<
0219                 Sig, T, std::initializer_list<U>&, Args...>::value>>
0220   explicit AnyInvocable(absl::in_place_type_t<T>,
0221                         std::initializer_list<U> ilist, Args&&... args)
0222       : Impl(absl::in_place_type<absl::decay_t<T>>, ilist,
0223              std::forward<Args>(args)...) {
0224     static_assert(std::is_same<T, absl::decay_t<T>>::value,
0225                   "The explicit template argument of in_place_type is required "
0226                   "to be an unqualified object type.");
0227   }
0228 
0229   // Assignment Operators
0230 
0231   // Assigns an `AnyInvocable` through move-assignment.
0232   // Note that `f` is not guaranteed to be empty after move-assignment
0233   // although it may be.
0234   AnyInvocable& operator=(AnyInvocable&& /*f*/) noexcept = default;
0235 
0236   // Assigns an `AnyInvocable` from a nullptr, clearing the `AnyInvocable`. If
0237   // not empty, destroys the target, putting `*this` into an empty state.
0238   AnyInvocable& operator=(std::nullptr_t) noexcept {
0239     this->Clear();
0240     return *this;
0241   }
0242 
0243   // Assigns an `AnyInvocable` from an existing `AnyInvocable` instance.
0244   //
0245   // Upon assignment, `*this` is only empty if `f` is a function pointer or
0246   // member pointer type and is null, or if `f` is an `AnyInvocable` that is
0247   // empty.
0248   template <class F, typename = absl::enable_if_t<
0249                          internal_any_invocable::CanAssign<Sig, F>::value>>
0250   AnyInvocable& operator=(F&& f) {
0251     *this = AnyInvocable(std::forward<F>(f));
0252     return *this;
0253   }
0254 
0255   // Assigns an `AnyInvocable` from a reference to an invocable object.
0256   // Upon assignment, stores a reference to the invocable object in the
0257   // `AnyInvocable` instance.
0258   template <
0259       class F,
0260       typename = absl::enable_if_t<
0261           internal_any_invocable::CanAssignReferenceWrapper<Sig, F>::value>>
0262   AnyInvocable& operator=(std::reference_wrapper<F> f) noexcept {
0263     *this = AnyInvocable(f);
0264     return *this;
0265   }
0266 
0267   // Destructor
0268 
0269   // If not empty, destroys the target.
0270   ~AnyInvocable() = default;
0271 
0272   // absl::AnyInvocable::swap()
0273   //
0274   // Exchanges the targets of `*this` and `other`.
0275   void swap(AnyInvocable& other) noexcept { std::swap(*this, other); }
0276 
0277   // absl::AnyInvocable::operator bool()
0278   //
0279   // Returns `true` if `*this` is not empty.
0280   //
0281   // WARNING: An `AnyInvocable` that wraps an empty `std::function` is not
0282   // itself empty. This behavior is consistent with the standard equivalent
0283   // `std::move_only_function`.
0284   //
0285   // In other words:
0286   //   std::function<void()> f;  // empty
0287   //   absl::AnyInvocable<void()> a = std::move(f);  // not empty
0288   //
0289   // Invoking an empty `AnyInvocable` results in undefined behavior.
0290   explicit operator bool() const noexcept { return this->HasValue(); }
0291 
0292   // Invokes the target object of `*this`. `*this` must not be empty.
0293   //
0294   // Note: The signature of this function call operator is the same as the
0295   //       template parameter `Sig`.
0296   using Impl::operator();
0297 
0298   // Equality operators
0299 
0300   // Returns `true` if `*this` is empty.
0301   friend bool operator==(const AnyInvocable& f, std::nullptr_t) noexcept {
0302     return !f.HasValue();
0303   }
0304 
0305   // Returns `true` if `*this` is empty.
0306   friend bool operator==(std::nullptr_t, const AnyInvocable& f) noexcept {
0307     return !f.HasValue();
0308   }
0309 
0310   // Returns `false` if `*this` is empty.
0311   friend bool operator!=(const AnyInvocable& f, std::nullptr_t) noexcept {
0312     return f.HasValue();
0313   }
0314 
0315   // Returns `false` if `*this` is empty.
0316   friend bool operator!=(std::nullptr_t, const AnyInvocable& f) noexcept {
0317     return f.HasValue();
0318   }
0319 
0320   // swap()
0321   //
0322   // Exchanges the targets of `f1` and `f2`.
0323   friend void swap(AnyInvocable& f1, AnyInvocable& f2) noexcept { f1.swap(f2); }
0324 
0325  private:
0326   // Friending other instantiations is necessary for conversions.
0327   template <bool /*SigIsNoexcept*/, class /*ReturnType*/, class... /*P*/>
0328   friend class internal_any_invocable::CoreImpl;
0329 };
0330 
0331 ABSL_NAMESPACE_END
0332 }  // namespace absl
0333 
0334 #endif  // ABSL_FUNCTIONAL_ANY_INVOCABLE_H_