2 * Copyright 2017-present 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.
17 * @author Eric Niebler (eniebler@fb.com), Sven Over (over@fb.com)
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>
227 #include <folly/Portability.h>
228 #include <folly/Traits.h>
229 #include <folly/functional/Invoke.h>
233 template <typename FunctionType>
236 template <typename ReturnType, typename... Args>
237 Function<ReturnType(Args...) const> constCastFunction(
238 Function<ReturnType(Args...)>&&) noexcept;
243 enum class Op { MOVE, NUKE, FULL, HEAP };
247 std::aligned_storage<6 * sizeof(void*)>::type tiny;
250 template <typename Fun, typename = Fun*>
251 using IsSmall = Conjunction<
252 std::integral_constant<bool, (sizeof(Fun) <= sizeof(Data::tiny))>,
253 std::is_nothrow_move_constructible<Fun>>;
254 using SmallTag = std::true_type;
255 using HeapTag = std::false_type;
257 template <typename T>
258 struct NotFunction : std::true_type {};
259 template <typename T>
260 struct NotFunction<Function<T>> : std::false_type {};
262 template <typename T>
263 using EnableIfNotFunction =
264 typename std::enable_if<NotFunction<T>::value>::type;
268 template <typename T>
269 bool isNullPtrFn(T* p) {
272 template <typename T>
273 std::false_type isNullPtrFn(T&&) {
277 inline bool uninitNoop(Op, Data*, Data*) {
281 template <typename FunctionType>
282 struct FunctionTraits;
284 template <typename ReturnType, typename... Args>
285 struct FunctionTraits<ReturnType(Args...)> {
286 using Call = ReturnType (*)(Data&, Args&&...);
287 using IsConst = std::false_type;
288 using ConstSignature = ReturnType(Args...) const;
289 using NonConstSignature = ReturnType(Args...);
290 using OtherSignature = ConstSignature;
292 template <typename F, typename G = typename std::decay<F>::type>
293 using ResultOf = decltype(
294 static_cast<ReturnType>(std::declval<G&>()(std::declval<Args>()...)));
296 template <typename Fun>
297 static ReturnType callSmall(Data& p, Args&&... args) {
298 return static_cast<ReturnType>((*static_cast<Fun*>(
299 static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
302 template <typename Fun>
303 static ReturnType callBig(Data& p, Args&&... args) {
304 return static_cast<ReturnType>(
305 (*static_cast<Fun*>(p.big))(static_cast<Args&&>(args)...));
308 static ReturnType uninitCall(Data&, Args&&...) {
309 throw std::bad_function_call();
312 ReturnType operator()(Args... args) {
313 auto& fn = *static_cast<Function<NonConstSignature>*>(this);
314 return fn.call_(fn.data_, static_cast<Args&&>(args)...);
318 std::shared_ptr<Function<NonConstSignature>> sp_;
321 explicit SharedProxy(Function<NonConstSignature>&& func)
322 : sp_(std::make_shared<Function<NonConstSignature>>(std::move(func))) {}
323 ReturnType operator()(Args&&... args) const {
324 return (*sp_)(static_cast<Args&&>(args)...);
329 template <typename ReturnType, typename... Args>
330 struct FunctionTraits<ReturnType(Args...) const> {
331 using Call = ReturnType (*)(Data&, Args&&...);
332 using IsConst = std::true_type;
333 using ConstSignature = ReturnType(Args...) const;
334 using NonConstSignature = ReturnType(Args...);
335 using OtherSignature = NonConstSignature;
337 template <typename F, typename G = typename std::decay<F>::type>
338 using ResultOf = decltype(static_cast<ReturnType>(
339 std::declval<const G&>()(std::declval<Args>()...)));
341 template <typename Fun>
342 static ReturnType callSmall(Data& p, Args&&... args) {
343 return static_cast<ReturnType>((*static_cast<const Fun*>(
344 static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
347 template <typename Fun>
348 static ReturnType callBig(Data& p, Args&&... args) {
349 return static_cast<ReturnType>(
350 (*static_cast<const Fun*>(p.big))(static_cast<Args&&>(args)...));
353 static ReturnType uninitCall(Data&, Args&&...) {
354 throw std::bad_function_call();
357 ReturnType operator()(Args... args) const {
358 auto& fn = *static_cast<const Function<ConstSignature>*>(this);
359 return fn.call_(fn.data_, static_cast<Args&&>(args)...);
363 std::shared_ptr<Function<ConstSignature>> sp_;
366 explicit SharedProxy(Function<ConstSignature>&& func)
367 : sp_(std::make_shared<Function<ConstSignature>>(std::move(func))) {}
368 ReturnType operator()(Args&&... args) const {
369 return (*sp_)(static_cast<Args&&>(args)...);
374 template <typename Fun>
375 bool execSmall(Op o, Data* src, Data* dst) {
378 ::new (static_cast<void*>(&dst->tiny))
379 Fun(std::move(*static_cast<Fun*>(static_cast<void*>(&src->tiny))));
382 static_cast<Fun*>(static_cast<void*>(&src->tiny))->~Fun();
392 template <typename Fun>
393 bool execBig(Op o, Data* src, Data* dst) {
400 delete static_cast<Fun*>(src->big);
409 } // namespace function
410 } // namespace detail
412 template <typename FunctionType>
413 class Function final : private detail::function::FunctionTraits<FunctionType> {
414 // These utility types are defined outside of the template to reduce
415 // the number of instantiations, and then imported in the class
416 // namespace for convenience.
417 using Data = detail::function::Data;
418 using Op = detail::function::Op;
419 using SmallTag = detail::function::SmallTag;
420 using HeapTag = detail::function::HeapTag;
421 using CoerceTag = detail::function::CoerceTag;
423 using Traits = detail::function::FunctionTraits<FunctionType>;
424 using Call = typename Traits::Call;
425 using Exec = bool (*)(Op, Data*, Data*);
427 template <typename Fun>
428 using IsSmall = detail::function::IsSmall<Fun>;
430 // The `data_` member is mutable to allow `constCastFunction` to work without
431 // invoking undefined behavior. Const-correctness is only violated when
432 // `FunctionType` is a const function type (e.g., `int() const`) and `*this`
433 // is the result of calling `constCastFunction`.
435 Call call_{&Traits::uninitCall};
436 Exec exec_{&detail::function::uninitNoop};
439 friend Function<typename Traits::ConstSignature> folly::constCastFunction<>(
440 Function<typename Traits::NonConstSignature>&&) noexcept;
441 friend class Function<typename Traits::OtherSignature>;
443 template <typename Fun>
444 Function(Fun&& fun, SmallTag) noexcept {
445 using FunT = typename std::decay<Fun>::type;
446 if (!detail::function::isNullPtrFn(fun)) {
447 ::new (static_cast<void*>(&data_.tiny)) FunT(static_cast<Fun&&>(fun));
448 call_ = &Traits::template callSmall<FunT>;
449 exec_ = &detail::function::execSmall<FunT>;
453 template <typename Fun>
454 Function(Fun&& fun, HeapTag) {
455 using FunT = typename std::decay<Fun>::type;
456 data_.big = new FunT(static_cast<Fun&&>(fun));
457 call_ = &Traits::template callBig<FunT>;
458 exec_ = &detail::function::execBig<FunT>;
461 template <typename Signature>
462 Function(Function<Signature>&& that, CoerceTag)
463 : Function(static_cast<Function<Signature>&&>(that), HeapTag{}) {}
466 Function<typename Traits::OtherSignature>&& that,
467 CoerceTag) noexcept {
468 that.exec_(Op::MOVE, &that.data_, &data_);
469 std::swap(call_, that.call_);
470 std::swap(exec_, that.exec_);
475 * Default constructor. Constructs an empty Function.
477 Function() = default;
480 Function(const Function&) = delete;
483 // Delete conversion from Objective-C blocks
484 template <class ReturnType, class... Args>
485 Function(ReturnType (^)(Args...)) = delete;
491 Function(Function&& that) noexcept {
492 that.exec_(Op::MOVE, &that.data_, &data_);
493 std::swap(call_, that.call_);
494 std::swap(exec_, that.exec_);
498 * Constructs an empty `Function`.
500 /* implicit */ Function(std::nullptr_t) noexcept {}
503 * Constructs a new `Function` from any callable object that is _not_ a
504 * `folly::Function`. This handles function pointers, pointers to static
505 * member functions, `std::reference_wrapper` objects, `std::function`
506 * objects, and arbitrary objects that implement `operator()` if the parameter
507 * signature matches (i.e. it returns an object convertible to `R` when called
510 * \note `typename = ResultOf<Fun>` prevents this overload from being
511 * selected by overload resolution when `fun` is not a compatible function.
513 * \note The noexcept requires some explanation. IsSmall is true when the
514 * decayed type fits within the internal buffer and is noexcept-movable. But
515 * this ctor might copy, not move. What we need here, if this ctor does a
516 * copy, is that this ctor be noexcept when the copy is noexcept. That is not
517 * checked in IsSmall, and shouldn't be, because once the Function is
518 * constructed, the contained object is never copied. This check is for this
519 * ctor only, in the case that this ctor does a copy.
523 typename = detail::function::EnableIfNotFunction<Fun>,
524 typename = typename Traits::template ResultOf<Fun>>
525 /* implicit */ Function(Fun fun) noexcept(
526 IsSmall<Fun>::value && noexcept(Fun(std::declval<Fun>())))
527 : Function(static_cast<Fun&&>(fun), IsSmall<Fun>{}) {}
530 * For move-constructing from a `folly::Function<X(Ys...) [const?]>`.
531 * For a `Function` with a `const` function type, the object must be
532 * callable from a `const`-reference, i.e. implement `operator() const`.
533 * For a `Function` with a non-`const` function type, the object will
534 * be called from a non-const reference, which means that it will execute
535 * a non-const `operator()` if it is defined, and falls back to
536 * `operator() const` otherwise.
540 typename = typename Traits::template ResultOf<Function<Signature>>>
541 Function(Function<Signature>&& that) noexcept(
542 noexcept(Function(std::move(that), CoerceTag{})))
543 : Function(std::move(that), CoerceTag{}) {}
546 * If `ptr` is null, constructs an empty `Function`. Otherwise,
547 * this constructor is equivalent to `Function(std::mem_fn(ptr))`.
552 // Prevent this overload from being selected when `ptr` is not a
553 // compatible member function pointer.
554 typename = decltype(Function(std::mem_fn((Member Class::*)0)))>
555 /* implicit */ Function(Member Class::*ptr) noexcept {
557 *this = std::mem_fn(ptr);
562 exec_(Op::NUKE, &data_, nullptr);
565 Function& operator=(const Function&) = delete;
568 // Delete conversion from Objective-C blocks
569 template <class ReturnType, class... Args>
570 Function& operator=(ReturnType (^)(Args...)) = delete;
574 * Move assignment operator
576 * \note Leaves `that` in a valid but unspecified state. If `&that == this`
577 * then `*this` is left in a valid but unspecified state.
579 Function& operator=(Function&& that) noexcept {
580 // Q: Why is it safe to destroy and reconstruct this object in place?
581 // A: Two reasons: First, `Function` is a final class, so in doing this
582 // we aren't slicing off any derived parts. And second, the move
583 // operation is guaranteed not to throw so we always leave the object
585 // In the case of self-move (this == &that), this leaves the object in
586 // a default-constructed state. First the object is destroyed, then we
587 // pass the destroyed object to the move constructor. The first thing the
588 // move constructor does is default-construct the object. That object is
589 // "moved" into itself, which is a no-op for a default-constructed Function.
591 ::new (this) Function(std::move(that));
596 * Assigns a callable object to this `Function`. If the operation fails,
597 * `*this` is left unmodified.
599 * \note `typename = ResultOf<Fun>` prevents this overload from being
600 * selected by overload resolution when `fun` is not a compatible function.
602 template <typename Fun, typename = decltype(Function(std::declval<Fun>()))>
603 Function& operator=(Fun fun) noexcept(
604 noexcept(/* implicit */ Function(std::declval<Fun>()))) {
605 // Doing this in place is more efficient when we can do so safely.
606 if (noexcept(/* implicit */ Function(std::declval<Fun>()))) {
607 // Q: Why is is safe to destroy and reconstruct this object in place?
608 // A: See the explanation in the move assignment operator.
610 ::new (this) Function(static_cast<Fun&&>(fun));
612 // Construct a temporary and (nothrow) swap.
613 Function(static_cast<Fun&&>(fun)).swap(*this);
619 * For assigning from a `Function<X(Ys..) [const?]>`.
623 typename = typename Traits::template ResultOf<Function<Signature>>>
624 Function& operator=(Function<Signature>&& that) noexcept(
625 noexcept(Function(std::move(that)))) {
626 return (*this = Function(std::move(that)));
630 * Clears this `Function`.
632 Function& operator=(std::nullptr_t) noexcept {
633 return (*this = Function());
637 * If `ptr` is null, clears this `Function`. Otherwise, this assignment
638 * operator is equivalent to `*this = std::mem_fn(ptr)`.
640 template <typename Member, typename Class>
641 auto operator=(Member Class::*ptr) noexcept
642 // Prevent this overload from being selected when `ptr` is not a
643 // compatible member function pointer.
644 -> decltype(operator=(std::mem_fn(ptr))) {
645 return ptr ? (*this = std::mem_fn(ptr)) : (*this = Function());
649 * Call the wrapped callable object with the specified arguments.
651 using Traits::operator();
654 * Exchanges the callable objects of `*this` and `that`.
656 void swap(Function& that) noexcept {
657 std::swap(*this, that);
661 * Returns `true` if this `Function` contains a callable, i.e. is
664 explicit operator bool() const noexcept {
665 return exec_(Op::FULL, nullptr, nullptr);
669 * Returns `true` if this `Function` stores the callable on the
670 * heap. If `false` is returned, there has been no additional memory
671 * allocation and the callable is stored inside the `Function`
674 bool hasAllocatedMemory() const noexcept {
675 return exec_(Op::HEAP, nullptr, nullptr);
678 using typename Traits::SharedProxy;
681 * Move this `Function` into a copyable callable object, of which all copies
684 SharedProxy asSharedProxy() && {
685 return SharedProxy{std::move(*this)};
689 * Construct a `std::function` by moving in the contents of this `Function`.
690 * Note that the returned `std::function` will share its state (i.e. captured
691 * data) across all copies you make of it, so be very careful when copying.
693 std::function<typename Traits::NonConstSignature> asStdFunction() && {
694 return std::move(*this).asSharedProxy();
698 template <typename FunctionType>
699 void swap(Function<FunctionType>& lhs, Function<FunctionType>& rhs) noexcept {
703 template <typename FunctionType>
704 bool operator==(const Function<FunctionType>& fn, std::nullptr_t) {
708 template <typename FunctionType>
709 bool operator==(std::nullptr_t, const Function<FunctionType>& fn) {
713 template <typename FunctionType>
714 bool operator!=(const Function<FunctionType>& fn, std::nullptr_t) {
715 return !(fn == nullptr);
718 template <typename FunctionType>
719 bool operator!=(std::nullptr_t, const Function<FunctionType>& fn) {
720 return !(nullptr == fn);
724 * NOTE: See detailed note about `constCastFunction` at the top of the file.
725 * This is potentially dangerous and requires the equivalent of a `const_cast`.
727 template <typename ReturnType, typename... Args>
728 Function<ReturnType(Args...) const> constCastFunction(
729 Function<ReturnType(Args...)>&& that) noexcept {
730 return Function<ReturnType(Args...) const>{std::move(that),
731 detail::function::CoerceTag{}};
734 template <typename ReturnType, typename... Args>
735 Function<ReturnType(Args...) const> constCastFunction(
736 Function<ReturnType(Args...) const>&& that) noexcept {
737 return std::move(that);
742 template <typename Fun, typename FunctionType, typename = void>
743 struct IsCallableAsImpl : std::false_type {};
745 template <typename Fun, typename ReturnType, typename... Args>
746 struct IsCallableAsImpl<
749 void_t<typename std::result_of<Fun && (Args && ...)>::type>>
750 : std::is_convertible<
751 typename std::result_of<Fun && (Args && ...)>::type,
754 template <typename Fun, typename FunctionType>
755 struct IsCallableAs : IsCallableAsImpl<Fun, FunctionType> {};
756 } // namespace function
757 } // namespace detail
762 * @brief A reference wrapper for callable objects
764 * FunctionRef is similar to std::reference_wrapper, but the template parameter
765 * is the function signature type rather than the type of the referenced object.
766 * A folly::FunctionRef is cheap to construct as it contains only a pointer to
767 * the referenced callable and a pointer to a function which invokes the
770 * The user of FunctionRef must be aware of the reference semantics: storing a
771 * copy of a FunctionRef is potentially dangerous and should be avoided unless
772 * the referenced object definitely outlives the FunctionRef object. Thus any
773 * function that accepts a FunctionRef parameter should only use it to invoke
774 * the referenced function and not store a copy of it. Knowing that FunctionRef
775 * itself has reference semantics, it is generally okay to use it to reference
776 * lambdas that capture by reference.
779 template <typename FunctionType>
782 template <typename ReturnType, typename... Args>
783 class FunctionRef<ReturnType(Args...)> final {
784 using Call = ReturnType (*)(void*, Args&&...);
786 static ReturnType uninitCall(void*, Args&&...) {
787 throw std::bad_function_call();
790 template <typename Fun>
791 static ReturnType call(void* object, Args&&... args) {
792 using Pointer = _t<std::add_pointer<Fun>>;
793 return static_cast<ReturnType>(invoke(
794 static_cast<Fun&&>(*static_cast<Pointer>(object)),
795 static_cast<Args&&>(args)...));
798 void* object_{nullptr};
799 Call call_{&FunctionRef::uninitCall};
803 * Default constructor. Constructs an empty FunctionRef.
805 * Invoking it will throw std::bad_function_call.
807 FunctionRef() = default;
810 * Construct a FunctionRef from a reference to a callable object.
814 typename std::enable_if<
816 Negation<std::is_same<FunctionRef, _t<std::decay<Fun>>>>,
817 detail::function::IsCallableAs<Fun, ReturnType(Args...)>>::value,
819 constexpr /* implicit */ FunctionRef(Fun&& fun) noexcept
820 // `Fun` may be a const type, in which case we have to do a const_cast
821 // to store the address in a `void*`. This is safe because the `void*`
822 // will be cast back to `Fun*` (which is a const pointer whenever `Fun`
823 // is a const type) inside `FunctionRef::call`
825 const_cast<void*>(static_cast<void const*>(std::addressof(fun)))),
826 call_(&FunctionRef::call<Fun>) {}
828 ReturnType operator()(Args... args) const {
829 return call_(object_, static_cast<Args&&>(args)...);
832 constexpr explicit operator bool() const {