2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 * @brief A polymorphic function wrapper that is not copyable and does not
21 * require the wrapped function to be copy constructible.
23 * `folly::Function` is a polymorphic function wrapper, similar to
24 * `std::function`. The template parameters of the `folly::Function` define
25 * the parameter signature of the wrapped callable, but not the specific
26 * type of the embedded callable. E.g. a `folly::Function<int(int)>`
27 * can wrap callables that return an `int` when passed an `int`. This can be a
28 * function pointer or any class object implementing one or both of
30 * int operator(int) const;
31 * If both are defined, the non-const one takes precedence.
33 * Unlike `std::function`, a `folly::Function` can wrap objects that are not
34 * copy constructible. As a consequence of this, `folly::Function` itself
35 * is not copyable, either.
37 * Another difference is that, unlike `std::function`, `folly::Function` treats
38 * const-ness of methods correctly. While a `std::function` allows to wrap
39 * an object that only implements a non-const `operator()` and invoke
40 * a const-reference of the `std::function`, `folly::Function` requires you to
41 * declare a function type as const in order to be able to execute it on a
48 * // mutates the Foo object
53 * std::function<void(void)> foo_; // wraps a Foo object
55 * void mutateFoo() const
60 * Even though `mutateFoo` is a const-method, so it can only reference `foo_`
61 * as const, it is able to call the non-const `operator()` of the Foo
62 * object that is embedded in the foo_ function.
64 * `folly::Function` will not allow you to do that. You will have to decide
65 * whether you need to invoke your wrapped callable from a const reference
66 * (like in the example above), in which case it will only wrap a
67 * `operator() const`. If your functor does not implement that,
68 * compilation will fail. If you do not require to be able to invoke the
69 * wrapped function in a const context, you can wrap any functor that
70 * implements either or both of const and non-const `operator()`.
72 * The first (and usually only specified) template parameter of
73 * `folly::Function`, the `FunctionType`, can be const-qualified. Be aware
74 * that the const is part of the function signature. It does not mean that
75 * the function type is a const type.
77 * using FunctionType = R(Args...);
78 * using ConstFunctionType = R(Args...) const;
80 * In this example, `FunctionType` and `ConstFunctionType` are different
81 * types. `ConstFunctionType` is not the same as `const FunctionType`.
82 * As a matter of fact, trying to use the latter should emit a compiler
83 * warning or error, because it has no defined meaning.
85 * // This will not compile:
86 * folly::Function<void(void) const> func = Foo();
87 * // because Foo does not have a member function of the form:
88 * // void operator()() const;
90 * // This will compile just fine:
91 * folly::Function<void(void)> func = Foo();
92 * // and it will wrap the existing member function:
93 * // void operator()();
95 * When should a const function type be used? As a matter of fact, you will
96 * probably not need to use const function types very often. See the following
100 * folly::Function<void()> func_;
101 * folly::Function<void() const> constFunc_;
103 * void someMethod() {
106 * // Can call constFunc_.
110 * void someConstMethod() const {
111 * // Can call constFunc_.
113 * // However, cannot call func_ because a non-const method cannot
114 * // be called from a const one.
118 * As you can see, whether the `folly::Function`'s function type should
119 * be declared const or not is identical to whether a corresponding method
120 * would be declared const or not.
122 * You only require a `folly::Function` to hold a const function type, if you
123 * intend to invoke it from within a const context. This is to ensure that
124 * you cannot mutate its inner state when calling in a const context.
126 * This is how the const/non-const choice relates to lambda functions:
128 * // Non-mutable lambdas: can be stored in a non-const...
129 * folly::Function<void(int)> print_number =
130 * [] (int number) { std::cout << number << std::endl; };
132 * // ...as well as in a const folly::Function
133 * folly::Function<void(int) const> print_number_const =
134 * [] (int number) { std::cout << number << std::endl; };
136 * // Mutable lambda: can only be stored in a non-const folly::Function:
138 * folly::Function<void()> print_number =
139 * [number] () mutable { std::cout << ++number << std::endl; };
140 * // Trying to store the above mutable lambda in a
141 * // `folly::Function<void() const>` would lead to a compiler error:
142 * // error: no viable conversion from '(lambda at ...)' to
143 * // 'folly::Function<void () const>'
145 * Casting between const and non-const `folly::Function`s:
146 * conversion from const to non-const signatures happens implicitly. Any
147 * function that takes a `folly::Function<R(Args...)>` can be passed
148 * a `folly::Function<R(Args...) const>` without explicit conversion.
149 * This is safe, because casting from const to non-const only entails giving
150 * up the ability to invoke the function from a const context.
151 * Casting from a non-const to a const signature is potentially dangerous,
152 * as it means that a function that may change its inner state when invoked
153 * is made possible to call from a const context. Therefore this cast does
154 * not happen implicitly. The function `folly::constCastfolly::Function` can
155 * be used to perform the cast.
157 * // Mutable lambda: can only be stored in a non-const folly::Function:
159 * folly::Function<void()> print_number =
160 * [number] () mutable { std::cout << ++number << std::endl; };
162 * // const-cast to a const folly::Function:
163 * folly::Function<void() const> print_number_const =
164 * constCastfolly::Function(std::move(print_number));
166 * When to use const function types?
167 * Generally, only when you need them. When you use a `folly::Function` as a
168 * member of a struct or class, only use a const function signature when you
169 * need to invoke the function from const context.
170 * When passing a `folly::Function` to a function, the function should accept
171 * a non-const `folly::Function` whenever possible, i.e. when it does not
172 * need to pass on or store a const `folly::Function`. This is the least
173 * possible constraint: you can always pass a const `folly::Function` when
174 * the function accepts a non-const one.
176 * How does the const behaviour compare to `std::function`?
177 * `std::function` can wrap object with non-const invokation behaviour but
178 * exposes them as const. The equivalent behaviour can be achieved with
179 * `folly::Function` like so:
181 * std::function<void(void)> stdfunc = someCallable;
183 * folly::Function<void(void) const> uniqfunc = constCastfolly::Function(
184 * folly::Function<void(void)>(someCallable)
187 * You need to wrap the callable first in a non-const `folly::Function` to
188 * select a non-const invoke operator (or the const one if no non-const one is
189 * present), and then move it into a const `folly::Function` using
190 * `constCastfolly::Function`.
191 * The name of `constCastfolly::Function` should warn you that something
192 * potentially dangerous is happening. As a matter of fact, using
193 * `std::function` always involves this potentially dangerous aspect, which
194 * is why it is not considered fully const-safe or even const-correct.
195 * However, in most of the cases you will not need the dangerous aspect at all.
196 * Either you do not require invokation of the function from a const context,
197 * in which case you do not need to use `constCastfolly::Function` and just
198 * use the inner `folly::Function` in the example above, i.e. just use a
199 * non-const `folly::Function`. Or, you may need invokation from const, but
200 * the callable you are wrapping does not mutate its state (e.g. it is a class
201 * object and implements `operator() const`, or it is a normal,
202 * non-mutable lambda), in which case you can wrap the callable in a const
203 * `folly::Function` directly, without using `constCastfolly::Function`.
204 * Only if you require invokation from a const context of a callable that
205 * may mutate itself when invoked you have to go through the above procedure.
206 * However, in that case what you do is potentially dangerous and requires
207 * the equivalent of a `const_cast`, hence you need to call
208 * `constCastfolly::Function`.
210 * `folly::Function` also has two additional template paremeters:
211 * * `NTM`: if set to `folly::FunctionMoveCtor::NO_THROW`, the
212 * `folly::Function` object is guaranteed to be nothrow move constructible.
213 * The downside is that any function object that itself is
214 * not nothrow move constructible cannot be stored in-place in the
215 * `folly::Function` object and will be stored on the heap instead.
216 * * `EmbedFunctorSize`: a number of bytes that will be reserved in the
217 * `folly::Function` object to store callable objects in-place. If you
218 * wrap a callable object bigger than this in a `folly::Function` object,
219 * it will be stored on the heap and the `folly::Function` object will keep
220 * a `std::unique_ptr` to it.
225 #include <functional>
226 #include <type_traits>
230 #include <folly/ScopeGuard.h>
231 #include <folly/portability/Constexpr.h>
235 enum class FunctionMoveCtor { NO_THROW, MAY_THROW };
238 typename FunctionType,
239 FunctionMoveCtor NTM = FunctionMoveCtor::NO_THROW,
240 size_t EmbedFunctorSize = (NTM == FunctionMoveCtor::NO_THROW)
241 ? sizeof(void (*)(void))
242 : sizeof(std::function<void(void)>)>
247 // boring predeclarations and details
248 #include "Function-pre.h"
252 template <typename FunctionType, FunctionMoveCtor NTM, size_t EmbedFunctorSize>
254 : public detail::function::FunctionTypeTraits<FunctionType>::
255 template InvokeOperator<
256 Function<FunctionType, NTM, EmbedFunctorSize>>,
257 public detail::function::MaybeUnaryOrBinaryFunction<FunctionType> {
259 using Traits = detail::function::FunctionTypeTraits<FunctionType>;
261 Traits::SuitableForFunction::value,
262 "Function<FunctionType>: FunctionType must be of the "
263 "form 'R(Args...)' or 'R(Args...) const'");
265 using ThisType = Function<FunctionType, NTM, EmbedFunctorSize>;
266 using InvokeOperator = typename Traits::template InvokeOperator<ThisType>;
268 static constexpr bool hasNoExceptMoveCtor() noexcept {
269 return NTM == FunctionMoveCtor::NO_THROW;
274 Function(Function const&) = delete;
275 Function& operator=(Function const&) = delete;
278 * Default constructor. Constructs an empty Function.
280 Function() noexcept {
281 initializeEmptyExecutor();
288 kStorageSize == sizeof(*this),
289 "There is something wrong with the size of Function");
292 // construct/assign from Function
296 Function(Function&& other) noexcept(hasNoExceptMoveCtor());
298 * Move assignment operator
300 Function& operator=(Function&& rhs) noexcept(hasNoExceptMoveCtor());
303 * Constructs a `Function` by moving from one with different template
304 * parameters with regards to const-ness, no-except-movability and internal
308 typename OtherFunctionType,
309 FunctionMoveCtor OtherNTM,
310 size_t OtherEmbedFunctorSize>
311 Function(Function<OtherFunctionType, OtherNTM, OtherEmbedFunctorSize>&& other)
313 OtherNTM == FunctionMoveCtor::NO_THROW &&
314 EmbedFunctorSize >= OtherEmbedFunctorSize);
317 * Moves a `Function` with different template parameters with regards
318 * to const-ness, no-except-movability and internal storage size into this
322 typename RhsFunctionType,
323 FunctionMoveCtor RhsNTM,
324 size_t RhsEmbedFunctorSize>
325 Function& operator=(Function<RhsFunctionType, RhsNTM, RhsEmbedFunctorSize>&&
326 rhs) noexcept(RhsNTM == FunctionMoveCtor::NO_THROW);
329 * Constructs an empty `Function`.
331 /* implicit */ Function(std::nullptr_t) noexcept : Function() {}
334 * Clears this `Function`.
336 Function& operator=(std::nullptr_t) noexcept {
338 initializeEmptyExecutor();
343 * Constructs a new `Function` from any callable object. This
344 * handles function pointers, pointers to static member functions,
345 * `std::reference_wrapper` objects, `std::function` objects, and arbitrary
346 * objects that implement `operator()` if the parameter signature
347 * matches (i.e. it returns R when called with Args...).
348 * For a `Function` with a const function type, the object must be
349 * callable from a const-reference, i.e. implement `operator() const`.
350 * For a `Function` with a non-const function type, the object will
351 * be called from a non-const reference, which means that it will execute
352 * a non-const `operator()` if it is defined, and falls back to
353 * `operator() const` otherwise
355 template <typename F>
356 /* implicit */ Function(
358 typename std::enable_if<
359 detail::function::IsCallable<F, FunctionType>::value>::type* =
360 0) noexcept(noexcept(typename std::decay<F>::
361 type(std::forward<F>(f)))) {
362 createExecutor(std::forward<F>(f));
366 * Assigns a callable object to this `Function`.
368 template <typename F>
369 typename std::enable_if<
370 detail::function::IsCallable<F, FunctionType>::value,
372 operator=(F&& f) noexcept(
373 noexcept(typename std::decay<F>::type(std::forward<F>(f)))) {
376 initializeEmptyExecutor();
378 createExecutor(std::forward<F>(f));
383 * Exchanges the callable objects of `*this` and `other`. `other` can be
384 * a Function with different settings with regard to
385 * no-except-movability and internal storage size, but must match
386 * `*this` with regards to return type and argument types.
388 template <FunctionMoveCtor OtherNTM, size_t OtherEmbedFunctorSize>
390 swap(Function<FunctionType, OtherNTM, OtherEmbedFunctorSize>& o) noexcept(
391 hasNoExceptMoveCtor() && OtherNTM == FunctionMoveCtor::NO_THROW);
394 * Returns `true` if this `Function` contains a callable, i.e. is
397 explicit operator bool() const noexcept;
400 * Returns `true` if this `Function` stores the callable on the
401 * heap. If `false` is returned, there has been no additional memory
402 * allocation and the callable is stored inside the `Function`
405 bool hasAllocatedMemory() const noexcept;
408 * Returns the `type_info` (as returned by `typeid`) of the callable stored
409 * in this `Function`. Returns `typeid(void)` if empty.
411 std::type_info const& target_type() const noexcept;
414 * Returns a pointer to the stored callable if its type matches `T`, and
415 * `nullptr` otherwise.
417 template <typename T>
418 T* target() noexcept;
421 * Returns a const-pointer to the stored callable if its type matches `T`,
422 * and `nullptr` otherwise.
424 template <typename T>
425 const T* target() const noexcept;
428 * Move out this `Function` into one with a const function type.
430 * This is a potentially dangerous operation, equivalent to a `const_cast`.
431 * This converts a `Function` with a non-const function type, i.e.
432 * one that can only be called when in the form of a non-const reference,
433 * into one that can be called in a const context. Use at your own risk!
435 Function<typename Traits::ConstFunctionType, NTM, EmbedFunctorSize>
436 castToConstFunction() && noexcept(hasNoExceptMoveCtor());
438 using SignatureType = FunctionType;
439 using ResultType = typename Traits::ResultType;
440 using ArgsTuple = typename Traits::ArgsTuple;
443 template <class, FunctionMoveCtor, size_t>
444 friend class Function;
446 friend struct detail::function::FunctionTypeTraits<FunctionType>;
449 typename detail::function::Executors<FunctionType>::ExecutorIf;
450 using EmptyExecutor =
451 typename detail::function::Executors<FunctionType>::EmptyExecutor;
452 template <typename F, typename SelectFunctionTag>
453 using FunctorPtrExecutor = typename detail::function::Executors<
454 FunctionType>::template FunctorPtrExecutor<F, SelectFunctionTag>;
455 template <typename F, typename SelectFunctionTag>
456 using FunctorExecutor = typename detail::function::Executors<
457 FunctionType>::template FunctorExecutor<F, SelectFunctionTag>;
459 template <typename T>
460 T const* access() const;
462 template <typename T>
465 void initializeEmptyExecutor() noexcept;
467 template <typename F>
468 void createExecutor(F&& f) noexcept(
469 noexcept(typename std::decay<F>::type(std::forward<F>(f))));
471 void destroyExecutor() noexcept;
473 struct MinStorageSize;
475 typename std::aligned_storage<MinStorageSize::value>::type data_;
476 static constexpr size_t kStorageSize = sizeof(data_);
480 template <typename FunctionType, FunctionMoveCtor NTM, size_t EmbedFunctorSize>
481 inline bool operator==(
482 Function<FunctionType, NTM, EmbedFunctorSize> const& f,
483 std::nullptr_t) noexcept {
487 template <typename FunctionType, FunctionMoveCtor NTM, size_t EmbedFunctorSize>
488 inline bool operator==(
490 Function<FunctionType, NTM, EmbedFunctorSize> const& f) noexcept {
494 template <typename FunctionType, FunctionMoveCtor NTM, size_t EmbedFunctorSize>
495 inline bool operator!=(
496 Function<FunctionType, NTM, EmbedFunctorSize> const& f,
497 std::nullptr_t) noexcept {
501 template <typename FunctionType, FunctionMoveCtor NTM, size_t EmbedFunctorSize>
502 inline bool operator!=(
504 Function<FunctionType, NTM, EmbedFunctorSize> const& f) noexcept {
509 * Cast a `Function` into one with a const function type.
511 * This is a potentially dangerous operation, equivalent to a `const_cast`.
512 * This converts a `Function` with a non-const function type, i.e.
513 * one that can only be called when in the form of a non-const reference,
514 * into one that can be called in a const context. Use at your own risk!
516 template <typename FunctionType, FunctionMoveCtor NTM, size_t EmbedFunctorSize>
518 typename detail::function::FunctionTypeTraits<
519 FunctionType>::ConstFunctionType,
522 constCastFunction(Function<FunctionType, NTM, EmbedFunctorSize>&&
523 from) noexcept(NTM == FunctionMoveCtor::NO_THROW) {
524 return std::move(from).castToConstFunction();
530 template <typename FunctionType, bool NOM1, bool NOM2, size_t S1, size_t S2>
532 ::folly::Function<FunctionType, NOM1, S1>& lhs,
533 ::folly::Function<FunctionType, NOM2, S2>& rhs) {
538 #include "Function-inl.h"