2 * Copyright 2016 Facebook, Inc.
4 * @author Eric Niebler (eniebler@fb.com), Sven Over (over@fb.com)
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * Acknowledgements: Giuseppe Ottaviano (ott@fb.com)
24 * @brief A polymorphic function wrapper that is not copyable and does not
25 * require the wrapped function to be copy constructible.
27 * `folly::Function` is a polymorphic function wrapper, similar to
28 * `std::function`. The template parameters of the `folly::Function` define
29 * the parameter signature of the wrapped callable, but not the specific
30 * type of the embedded callable. E.g. a `folly::Function<int(int)>`
31 * can wrap callables that return an `int` when passed an `int`. This can be a
32 * function pointer or any class object implementing one or both of
35 * int operator(int) const;
37 * If both are defined, the non-const one takes precedence.
39 * Unlike `std::function`, a `folly::Function` can wrap objects that are not
40 * copy constructible. As a consequence of this, `folly::Function` itself
41 * is not copyable, either.
43 * Another difference is that, unlike `std::function`, `folly::Function` treats
44 * const-ness of methods correctly. While a `std::function` allows to wrap
45 * an object that only implements a non-const `operator()` and invoke
46 * a const-reference of the `std::function`, `folly::Function` requires you to
47 * declare a function type as const in order to be able to execute it on a
55 * // mutates the Foo object
60 * std::function<void(void)> foo_; // wraps a Foo object
62 * void mutateFoo() const
68 * Even though `mutateFoo` is a const-method, so it can only reference `foo_`
69 * as const, it is able to call the non-const `operator()` of the Foo
70 * object that is embedded in the foo_ function.
72 * `folly::Function` will not allow you to do that. You will have to decide
73 * whether you need to invoke your wrapped callable from a const reference
74 * (like in the example above), in which case it will only wrap a
75 * `operator() const`. If your functor does not implement that,
76 * compilation will fail. If you do not require to be able to invoke the
77 * wrapped function in a const context, you can wrap any functor that
78 * implements either or both of const and non-const `operator()`.
80 * The template parameter of `folly::Function`, the `FunctionType`, can be
81 * const-qualified. Be aware that the const is part of the function signature.
82 * It does not mean that the function type is a const type.
84 * using FunctionType = R(Args...);
85 * using ConstFunctionType = R(Args...) const;
87 * In this example, `FunctionType` and `ConstFunctionType` are different
88 * types. `ConstFunctionType` is not the same as `const FunctionType`.
89 * As a matter of fact, trying to use the latter should emit a compiler
90 * warning or error, because it has no defined meaning.
92 * // This will not compile:
93 * folly::Function<void(void) const> func = Foo();
94 * // because Foo does not have a member function of the form:
95 * // void operator()() const;
97 * // This will compile just fine:
98 * folly::Function<void(void)> func = Foo();
99 * // and it will wrap the existing member function:
100 * // void operator()();
102 * When should a const function type be used? As a matter of fact, you will
103 * probably not need to use const function types very often. See the following
107 * folly::Function<void()> func_;
108 * folly::Function<void() const> constFunc_;
110 * void someMethod() {
113 * // Can call constFunc_.
117 * void someConstMethod() const {
118 * // Can call constFunc_.
120 * // However, cannot call func_ because a non-const method cannot
121 * // be called from a const one.
125 * As you can see, whether the `folly::Function`'s function type should
126 * be declared const or not is identical to whether a corresponding method
127 * would be declared const or not.
129 * You only require a `folly::Function` to hold a const function type, if you
130 * intend to invoke it from within a const context. This is to ensure that
131 * you cannot mutate its inner state when calling in a const context.
133 * This is how the const/non-const choice relates to lambda functions:
135 * // Non-mutable lambdas: can be stored in a non-const...
136 * folly::Function<void(int)> print_number =
137 * [] (int number) { std::cout << number << std::endl; };
139 * // ...as well as in a const folly::Function
140 * folly::Function<void(int) const> print_number_const =
141 * [] (int number) { std::cout << number << std::endl; };
143 * // Mutable lambda: can only be stored in a non-const folly::Function:
145 * folly::Function<void()> print_number =
146 * [number] () mutable { std::cout << ++number << std::endl; };
147 * // Trying to store the above mutable lambda in a
148 * // `folly::Function<void() const>` would lead to a compiler error:
149 * // error: no viable conversion from '(lambda at ...)' to
150 * // 'folly::Function<void () const>'
152 * Casting between const and non-const `folly::Function`s:
153 * conversion from const to non-const signatures happens implicitly. Any
154 * function that takes a `folly::Function<R(Args...)>` can be passed
155 * a `folly::Function<R(Args...) const>` without explicit conversion.
156 * This is safe, because casting from const to non-const only entails giving
157 * up the ability to invoke the function from a const context.
158 * Casting from a non-const to a const signature is potentially dangerous,
159 * as it means that a function that may change its inner state when invoked
160 * is made possible to call from a const context. Therefore this cast does
161 * not happen implicitly. The function `folly::constCastFunction` can
162 * be used to perform the cast.
164 * // Mutable lambda: can only be stored in a non-const folly::Function:
166 * folly::Function<void()> print_number =
167 * [number] () mutable { std::cout << ++number << std::endl; };
169 * // const-cast to a const folly::Function:
170 * folly::Function<void() const> print_number_const =
171 * constCastFunction(std::move(print_number));
173 * When to use const function types?
174 * Generally, only when you need them. When you use a `folly::Function` as a
175 * member of a struct or class, only use a const function signature when you
176 * need to invoke the function from const context.
177 * When passing a `folly::Function` to a function, the function should accept
178 * a non-const `folly::Function` whenever possible, i.e. when it does not
179 * need to pass on or store a const `folly::Function`. This is the least
180 * possible constraint: you can always pass a const `folly::Function` when
181 * the function accepts a non-const one.
183 * How does the const behaviour compare to `std::function`?
184 * `std::function` can wrap object with non-const invokation behaviour but
185 * exposes them as const. The equivalent behaviour can be achieved with
186 * `folly::Function` like so:
188 * std::function<void(void)> stdfunc = someCallable;
190 * folly::Function<void(void) const> uniqfunc = constCastFunction(
191 * folly::Function<void(void)>(someCallable)
194 * You need to wrap the callable first in a non-const `folly::Function` to
195 * select a non-const invoke operator (or the const one if no non-const one is
196 * present), and then move it into a const `folly::Function` using
197 * `constCastFunction`.
198 * The name of `constCastFunction` should warn you that something
199 * potentially dangerous is happening. As a matter of fact, using
200 * `std::function` always involves this potentially dangerous aspect, which
201 * is why it is not considered fully const-safe or even const-correct.
202 * However, in most of the cases you will not need the dangerous aspect at all.
203 * Either you do not require invokation of the function from a const context,
204 * in which case you do not need to use `constCastFunction` and just
205 * use the inner `folly::Function` in the example above, i.e. just use a
206 * non-const `folly::Function`. Or, you may need invokation from const, but
207 * the callable you are wrapping does not mutate its state (e.g. it is a class
208 * object and implements `operator() const`, or it is a normal,
209 * non-mutable lambda), in which case you can wrap the callable in a const
210 * `folly::Function` directly, without using `constCastFunction`.
211 * Only if you require invokation from a const context of a callable that
212 * may mutate itself when invoked you have to go through the above procedure.
213 * However, in that case what you do is potentially dangerous and requires
214 * the equivalent of a `const_cast`, hence you need to call
215 * `constCastFunction`.
220 #include <functional>
223 #include <type_traits>
226 #include <folly/CppAttributes.h>
231 template <typename FunctionType, bool Const = false>
234 template <typename ReturnType, typename... Args>
235 Function<ReturnType(Args...), true> constCastFunction(
236 Function<ReturnType(Args...), false>&&) noexcept;
242 enum class Op { MOVE, NUKE, FULL, HEAP };
246 typename std::aligned_storage<6 * sizeof(void*)>::type small;
249 template <bool If, typename T>
250 using ConstIf = typename std::conditional<If, const T, T>::type;
252 template <typename Fun, typename FunT = typename std::decay<Fun>::type>
253 using IsSmall = std::integral_constant<
255 (sizeof(FunT) <= sizeof(Data::small) &&
256 // Same as is_nothrow_move_constructible, but w/ no template instantiation.
257 noexcept(FunT(std::declval<FunT&&>()))
259 using SmallTag = std::true_type;
260 using HeapTag = std::false_type;
262 template <typename T>
263 bool isNullPtrFn(T* p) {
266 template <typename T>
267 std::false_type isNullPtrFn(T&&) {
271 template <typename ReturnType, typename... Args>
272 ReturnType uninitCall(Data&, Args&&...) {
273 throw std::bad_function_call();
275 inline bool uninitNoop(Op, Data*, Data*) {
279 } // namespace function
280 } // namespace detail
284 template <typename ReturnType, typename... Args, bool Const>
285 class Function<ReturnType(Args...), Const> final {
286 // These utility types are defined outside of the template to reduce
287 // the number of instantiations, and then imported in the class
288 // namespace for convenience.
289 using Data = detail::function::Data;
290 using Op = detail::function::Op;
291 using SmallTag = detail::function::SmallTag;
292 using HeapTag = detail::function::HeapTag;
293 using Call = ReturnType (*)(Data&, Args&&...);
294 using Exec = bool (*)(Op, Data*, Data*);
296 template <typename T>
297 using ConstIf = detail::function::ConstIf<Const, T>;
298 template <typename Fun>
299 using IsSmall = detail::function::IsSmall<Fun>;
302 * @Function is const-safe:
303 * - @call_ takes @Data as non-const param to avoid code/data duplication.
304 * - @data_ can only be mutated if @constCastFunction is used.
307 Call call_{&detail::function::uninitCall<ReturnType, Args...>};
308 Exec exec_{&detail::function::uninitNoop};
310 friend Function<ReturnType(Args...), true> constCastFunction<>(
311 Function<ReturnType(Args...), false>&&) noexcept;
312 friend class Function<ReturnType(Args...), !Const>;
314 template <typename Fun>
316 using FunT = typename std::decay<Fun>::type;
317 static ReturnType call(Data& p, Args&&... args) {
318 return static_cast<ReturnType>((*static_cast<ConstIf<FunT>*>(
319 static_cast<void*>(&p.small)))(static_cast<Args&&>(args)...));
321 static bool exec(Op o, Data* src, Data* dst) {
324 ::new (static_cast<void*>(&dst->small)) FunT(
325 std::move(*static_cast<FunT*>(static_cast<void*>(&src->small))));
328 static_cast<FunT*>(static_cast<void*>(&src->small))->~FunT();
339 template <typename Fun>
340 Function(Fun&& fun, SmallTag) noexcept {
341 using Ops = OpsSmall<Fun>;
342 if (!detail::function::isNullPtrFn(fun)) {
343 ::new (static_cast<void*>(&data_.small))
344 typename Ops::FunT(static_cast<Fun&&>(fun));
350 template <typename Fun>
352 using FunT = typename std::decay<Fun>::type;
353 static ReturnType call(Data& p, Args&&... args) {
354 return static_cast<ReturnType>(
355 (*static_cast<ConstIf<FunT>*>(p.big))(static_cast<Args&&>(args)...));
357 static bool exec(Op o, Data* src, Data* dst) {
364 delete static_cast<FunT*>(src->big);
374 template <typename Fun>
375 Function(Fun&& fun, HeapTag) {
376 using Ops = OpsHeap<Fun>;
377 data_.big = new typename Ops::FunT(static_cast<Fun&&>(fun));
382 template <typename F, typename G = typename std::decay<F>::type>
383 using ResultOf = decltype(static_cast<ReturnType>(
384 std::declval<ConstIf<G>&>()(std::declval<Args>()...)));
388 * Default constructor. Constructs an empty Function.
390 Function() = default;
393 // NOTE: Deleting the non-const copy constructor is unusual but necessary to
394 // prevent copies from non-const `Function` object from selecting the
395 // perfect forwarding implicit converting constructor below
396 // (i.e., `template <typename Fun> Function(Fun&&)`).
397 Function(Function&) = delete;
398 Function(const Function&) = delete;
403 Function(Function&& that) noexcept {
404 that.exec_(Op::MOVE, &that.data_, &data_);
405 std::swap(call_, that.call_);
406 std::swap(exec_, that.exec_);
410 * Constructs an empty `Function`.
412 /* implicit */ Function(std::nullptr_t) noexcept {}
415 * Constructs a new `Function` from any callable object. This
416 * handles function pointers, pointers to static member functions,
417 * `std::reference_wrapper` objects, `std::function` objects, and arbitrary
418 * objects that implement `operator()` if the parameter signature
419 * matches (i.e. it returns R when called with Args...).
420 * For a `Function` with a const function type, the object must be
421 * callable from a const-reference, i.e. implement `operator() const`.
422 * For a `Function` with a non-const function type, the object will
423 * be called from a non-const reference, which means that it will execute
424 * a non-const `operator()` if it is defined, and falls back to
425 * `operator() const` otherwise.
427 * \note `typename = ResultOf<Fun>` prevents this overload from being
428 * selected by overload resolution when `fun` is not a compatible function.
430 template <class Fun, typename = ResultOf<Fun>>
431 /* implicit */ Function(Fun&& fun) noexcept(IsSmall<Fun>::value)
432 : Function(static_cast<Fun&&>(fun), IsSmall<Fun>{}) {}
435 * For moving a `Function<X(Ys..) const>` into a `Function<X(Ys...)>`.
439 typename std::enable_if<!Const && OtherConst, int>::type = 0>
440 Function(Function<ReturnType(Args...), OtherConst>&& that) noexcept {
441 that.exec_(Op::MOVE, &that.data_, &data_);
442 std::swap(call_, that.call_);
443 std::swap(exec_, that.exec_);
447 * If `ptr` is null, constructs an empty `Function`. Otherwise,
448 * this constructor is equivalent to `Function(std::mem_fn(ptr))`.
453 // Prevent this overload from being selected when `ptr` is not a
454 // compatible member function pointer.
455 typename = decltype(Function(std::mem_fn((Member Class::*)0)))>
456 /* implicit */ Function(Member Class::*ptr) noexcept {
458 *this = std::mem_fn(ptr);
463 exec_(Op::NUKE, &data_, nullptr);
466 Function& operator=(Function&) = delete;
467 Function& operator=(const Function&) = delete;
470 * Move assignment operator
472 Function& operator=(Function&& that) noexcept {
474 // Q: Why is is safe to destroy and reconstruct this object in place?
475 // A: Two reasons: First, `Function` is a final class, so in doing this
476 // we aren't slicing off any derived parts. And second, the move
477 // operation is guaranteed not to throw so we always leave the object
480 ::new (this) Function(std::move(that));
486 * Assigns a callable object to this `Function`. If the operation fails,
487 * `*this` is left unmodified.
489 * \note `typename = ResultOf<Fun>` prevents this overload from being
490 * selected by overload resolution when `fun` is not a compatible function.
492 template <class Fun, typename = ResultOf<Fun>>
493 Function& operator=(Fun&& fun) noexcept(
494 noexcept(/* implicit */ Function(std::declval<Fun>()))) {
495 // Doing this in place is more efficient when we can do so safely.
496 if (noexcept(/* implicit */ Function(std::declval<Fun>()))) {
497 // Q: Why is is safe to destroy and reconstruct this object in place?
498 // A: See the explanation in the move assignment operator.
500 ::new (this) Function(static_cast<Fun&&>(fun));
502 // Construct a temporary and (nothrow) swap.
503 Function(static_cast<Fun&&>(fun)).swap(*this);
509 * Clears this `Function`.
511 Function& operator=(std::nullptr_t) noexcept {
512 return (*this = Function());
516 * If `ptr` is null, clears this `Function`. Otherwise, this assignment
517 * operator is equivalent to `*this = std::mem_fn(ptr)`.
519 template <typename Member, typename Class>
520 auto operator=(Member Class::*ptr) noexcept
521 // Prevent this overload from being selected when `ptr` is not a
522 // compatible member function pointer.
523 -> decltype(operator=(std::mem_fn(ptr))) {
524 return ptr ? (*this = std::mem_fn(ptr)) : (*this = Function());
528 * Call the wrapped callable object with the specified arguments.
529 * If this `Function` object is a const `folly::Function` object,
530 * this overload shall not participate in overload resolution.
533 // `True` makes `operator()` a template so we can SFINAE on `Const`,
534 // which is non-deduced here.
536 typename std::enable_if<True && !Const, int>::type = 0>
537 ReturnType operator()(Args... args) {
538 return call_(data_, static_cast<Args&&>(args)...);
542 * Call the wrapped callable object with the specified arguments.
543 * If this `Function` object is not a const `folly::Function` object,
544 * this overload shall not participate in overload resolution.
547 // `True` makes `operator()` a template so we can SFINAE on `Const`,
548 // which is non-deduced here.
550 typename std::enable_if<True && Const, int>::type = 0>
551 ReturnType operator()(Args... args) const {
552 return call_(data_, static_cast<Args&&>(args)...);
556 * Exchanges the callable objects of `*this` and `that`.
558 void swap(Function& that) noexcept {
559 std::swap(*this, that);
563 * Returns `true` if this `Function` contains a callable, i.e. is
566 explicit operator bool() const noexcept {
567 return exec_(Op::FULL, nullptr, nullptr);
571 * Returns `true` if this `Function` stores the callable on the
572 * heap. If `false` is returned, there has been no additional memory
573 * allocation and the callable is stored inside the `Function`
576 bool hasAllocatedMemory() const noexcept {
577 return exec_(Op::HEAP, nullptr, nullptr);
581 * Construct a `std::function` by moving in the contents of this `Function`.
582 * Note that the returned `std::function` will share its state (i.e. captured
583 * data) across all copies you make of it, so be very careful when copying.
585 std::function<ReturnType(Args...)> asStdFunction() && {
587 std::shared_ptr<Function> sp_;
588 ReturnType operator()(Args&&... args) const {
589 return (*sp_)(static_cast<Args&&>(args)...);
592 return Impl{std::make_shared<Function>(std::move(*this))};
596 template <typename FunctionType, bool Const>
598 Function<FunctionType, Const>& lhs,
599 Function<FunctionType, Const>& rhs) noexcept {
603 template <typename FunctionType, bool Const>
604 bool operator==(const Function<FunctionType, Const>& fn, std::nullptr_t) {
608 template <typename FunctionType, bool Const>
609 bool operator==(std::nullptr_t, const Function<FunctionType, Const>& fn) {
613 template <typename FunctionType, bool Const>
614 bool operator!=(const Function<FunctionType, Const>& fn, std::nullptr_t) {
615 return !(fn == nullptr);
618 template <typename FunctionType, bool Const>
619 bool operator!=(std::nullptr_t, const Function<FunctionType, Const>& fn) {
620 return !(nullptr == fn);
624 * NOTE: See detailed note about @constCastFunction at the top of the file.
625 * This is potentially dangerous and requires the equivalent of a `const_cast`.
627 template <typename ReturnType, typename... Args>
628 Function<ReturnType(Args...), true> constCastFunction(
629 Function<ReturnType(Args...), false>&& that) noexcept {
630 Function<ReturnType(Args...), true> fn{};
631 that.exec_(detail::function::Op::MOVE, &that.data_, &fn.data_);
632 std::swap(fn.call_, that.call_);
633 std::swap(fn.exec_, that.exec_);
637 template <typename FunctionType>
638 Function<FunctionType, true> constCastFunction(
639 Function<FunctionType, true>&& that) noexcept {
640 return std::move(that);
643 template <typename FunctionType>
644 struct MakeFunction {};
646 template <typename ReturnType, typename... Args>
647 struct MakeFunction<ReturnType(Args...)> {
648 using type = Function<ReturnType(Args...), false>;
651 template <typename ReturnType, typename... Args>
652 struct MakeFunction<ReturnType(Args...) const> {
653 using type = Function<ReturnType(Args...), true>;
657 /* using override */ using impl::constCastFunction;
659 template <typename FunctionType>
660 using Function = typename impl::MakeFunction<FunctionType>::type;