Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2024-11-15 09:01:03

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