Properly constrain folly::Function's generic conversion constructor and fix its noexc...
[folly.git] / folly / Function.h
1 /*
2  * Copyright 2017-present Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 /*
17  * @author Eric Niebler (eniebler@fb.com), Sven Over (over@fb.com)
18  * Acknowledgements: Giuseppe Ottaviano (ott@fb.com)
19  */
20
21 /**
22  * @class Function
23  *
24  * @brief A polymorphic function wrapper that is not copyable and does not
25  *    require the wrapped function to be copy constructible.
26  *
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
33  *
34  *     int operator(int);
35  *     int operator(int) const;
36  *
37  * If both are defined, the non-const one takes precedence.
38  *
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.
42  *
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
48  * const-reference.
49  *
50  * For example:
51  *
52  *     class Foo {
53  *      public:
54  *       void operator()() {
55  *         // mutates the Foo object
56  *       }
57  *     };
58  *
59  *     class Bar {
60  *       std::function<void(void)> foo_; // wraps a Foo object
61  *      public:
62  *       void mutateFoo() const
63  *       {
64  *         foo_();
65  *       }
66  *     };
67  *
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.
71  *
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()`.
79  *
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.
83  *
84  *   using FunctionType = R(Args...);
85  *   using ConstFunctionType = R(Args...) const;
86  *
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.
91  *
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;
96  *
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()();
101  *
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
104  * example:
105  *
106  *     class Bar {
107  *       folly::Function<void()> func_;
108  *       folly::Function<void() const> constFunc_;
109  *
110  *       void someMethod() {
111  *         // Can call func_.
112  *         func_();
113  *         // Can call constFunc_.
114  *         constFunc_();
115  *       }
116  *
117  *       void someConstMethod() const {
118  *         // Can call constFunc_.
119  *         constFunc_();
120  *         // However, cannot call func_ because a non-const method cannot
121  *         // be called from a const one.
122  *       }
123  *     };
124  *
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.
128  *
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.
132  *
133  * This is how the const/non-const choice relates to lambda functions:
134  *
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; };
138  *
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; };
142  *
143  *     // Mutable lambda: can only be stored in a non-const folly::Function:
144  *     int number = 0;
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>'
151  *
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.
163  *
164  *     // Mutable lambda: can only be stored in a non-const folly::Function:
165  *     int number = 0;
166  *     folly::Function<void()> print_number =
167  *       [number] () mutable { std::cout << ++number << std::endl; };
168  *
169  *     // const-cast to a const folly::Function:
170  *     folly::Function<void() const> print_number_const =
171  *       constCastFunction(std::move(print_number));
172  *
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.
182  *
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:
187  *
188  *     std::function<void(void)> stdfunc = someCallable;
189  *
190  *     folly::Function<void(void) const> uniqfunc = constCastFunction(
191  *       folly::Function<void(void)>(someCallable)
192  *     );
193  *
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`.
216  */
217
218 #pragma once
219
220 #include <functional>
221 #include <memory>
222 #include <new>
223 #include <type_traits>
224 #include <utility>
225
226 #include <folly/CppAttributes.h>
227 #include <folly/Portability.h>
228 #include <folly/Traits.h>
229
230 namespace folly {
231
232 template <typename FunctionType>
233 class Function;
234
235 template <typename ReturnType, typename... Args>
236 Function<ReturnType(Args...) const> constCastFunction(
237     Function<ReturnType(Args...)>&&) noexcept;
238
239 namespace detail {
240 namespace function {
241
242 enum class Op { MOVE, NUKE, FULL, HEAP };
243
244 union Data {
245   void* big;
246   std::aligned_storage<6 * sizeof(void*)>::type tiny;
247 };
248
249 template <typename Fun, typename FunT = typename std::decay<Fun>::type>
250 using IsSmall = Conjunction<
251     std::integral_constant<bool, (sizeof(FunT) <= sizeof(Data::tiny))>,
252     std::is_nothrow_move_constructible<FunT>>;
253 using SmallTag = std::true_type;
254 using HeapTag = std::false_type;
255
256 template <class T>
257 struct NotFunction : std::true_type {};
258 template <class T>
259 struct NotFunction<Function<T>> : std::false_type {};
260
261 template <typename Fun, typename FunT = typename std::decay<Fun>::type>
262 using DecayIfConstructible = typename std::enable_if<
263     Conjunction<NotFunction<FunT>, std::is_constructible<FunT, Fun>>::value,
264     FunT>::type;
265
266 struct CoerceTag {};
267
268 template <typename T>
269 bool isNullPtrFn(T* p) {
270   return p == nullptr;
271 }
272 template <typename T>
273 std::false_type isNullPtrFn(T&&) {
274   return {};
275 }
276
277 inline bool uninitNoop(Op, Data*, Data*) {
278   return false;
279 }
280
281 template <typename FunctionType>
282 struct FunctionTraits;
283
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;
291
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>()...)));
295
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)...));
300   }
301
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)...));
306   }
307
308   static ReturnType uninitCall(Data&, Args&&...) {
309     throw std::bad_function_call();
310   }
311
312   ReturnType operator()(Args... args) {
313     auto& fn = *static_cast<Function<ReturnType(Args...)>*>(this);
314     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
315   }
316
317   class SharedProxy {
318     std::shared_ptr<Function<ReturnType(Args...)>> sp_;
319
320    public:
321     explicit SharedProxy(Function<ReturnType(Args...)>&& func)
322         : sp_(std::make_shared<Function<ReturnType(Args...)>>(
323               std::move(func))) {}
324     ReturnType operator()(Args&&... args) const {
325       return (*sp_)(static_cast<Args&&>(args)...);
326     }
327   };
328 };
329
330 template <typename ReturnType, typename... Args>
331 struct FunctionTraits<ReturnType(Args...) const> {
332   using Call = ReturnType (*)(Data&, Args&&...);
333   using IsConst = std::true_type;
334   using ConstSignature = ReturnType(Args...) const;
335   using NonConstSignature = ReturnType(Args...);
336   using OtherSignature = NonConstSignature;
337
338   template <typename F, typename G = typename std::decay<F>::type>
339   using ResultOf = decltype(static_cast<ReturnType>(
340       std::declval<const G&>()(std::declval<Args>()...)));
341
342   template <typename Fun>
343   static ReturnType callSmall(Data& p, Args&&... args) {
344     return static_cast<ReturnType>((*static_cast<const Fun*>(
345         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
346   }
347
348   template <typename Fun>
349   static ReturnType callBig(Data& p, Args&&... args) {
350     return static_cast<ReturnType>(
351         (*static_cast<const Fun*>(p.big))(static_cast<Args&&>(args)...));
352   }
353
354   static ReturnType uninitCall(Data&, Args&&...) {
355     throw std::bad_function_call();
356   }
357
358   ReturnType operator()(Args... args) const {
359     auto& fn = *static_cast<const Function<ReturnType(Args...) const>*>(this);
360     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
361   }
362
363   class SharedProxy {
364     std::shared_ptr<Function<ReturnType(Args...) const>> sp_;
365
366    public:
367     explicit SharedProxy(Function<ReturnType(Args...) const>&& func)
368         : sp_(std::make_shared<Function<ReturnType(Args...) const>>(
369               std::move(func))) {}
370     ReturnType operator()(Args&&... args) const {
371       return (*sp_)(static_cast<Args&&>(args)...);
372     }
373   };
374 };
375
376 template <typename Fun>
377 bool execSmall(Op o, Data* src, Data* dst) {
378   switch (o) {
379     case Op::MOVE:
380       ::new (static_cast<void*>(&dst->tiny))
381           Fun(std::move(*static_cast<Fun*>(static_cast<void*>(&src->tiny))));
382       FOLLY_FALLTHROUGH;
383     case Op::NUKE:
384       static_cast<Fun*>(static_cast<void*>(&src->tiny))->~Fun();
385       break;
386     case Op::FULL:
387       return true;
388     case Op::HEAP:
389       break;
390   }
391   return false;
392 }
393
394 template <typename Fun>
395 bool execBig(Op o, Data* src, Data* dst) {
396   switch (o) {
397     case Op::MOVE:
398       dst->big = src->big;
399       src->big = nullptr;
400       break;
401     case Op::NUKE:
402       delete static_cast<Fun*>(src->big);
403       break;
404     case Op::FULL:
405     case Op::HEAP:
406       break;
407   }
408   return true;
409 }
410
411 // Invoke helper
412 template <typename F, typename... Args>
413 inline auto invoke(F&& f, Args&&... args)
414     -> decltype(std::forward<F>(f)(std::forward<Args>(args)...)) {
415   return std::forward<F>(f)(std::forward<Args>(args)...);
416 }
417
418 template <typename M, typename C, typename... Args>
419 inline auto invoke(M(C::*d), Args&&... args)
420     -> decltype(std::mem_fn(d)(std::forward<Args>(args)...)) {
421   return std::mem_fn(d)(std::forward<Args>(args)...);
422 }
423
424 } // namespace function
425 } // namespace detail
426
427 FOLLY_PUSH_WARNING
428 FOLLY_MSVC_DISABLE_WARNING(4521) // Multiple copy constructors
429 FOLLY_MSVC_DISABLE_WARNING(4522) // Multiple assignment operators
430 template <typename FunctionType>
431 class Function final : private detail::function::FunctionTraits<FunctionType> {
432   // These utility types are defined outside of the template to reduce
433   // the number of instantiations, and then imported in the class
434   // namespace for convenience.
435   using Data = detail::function::Data;
436   using Op = detail::function::Op;
437   using SmallTag = detail::function::SmallTag;
438   using HeapTag = detail::function::HeapTag;
439   using CoerceTag = detail::function::CoerceTag;
440
441   using Traits = detail::function::FunctionTraits<FunctionType>;
442   using Call = typename Traits::Call;
443   using Exec = bool (*)(Op, Data*, Data*);
444
445   template <typename Fun>
446   using IsSmall = detail::function::IsSmall<Fun>;
447
448   // The `data_` member is mutable to allow `constCastFunction` to work without
449   // invoking undefined behavior. Const-correctness is only violated when
450   // `FunctionType` is a const function type (e.g., `int() const`) and `*this`
451   // is the result of calling `constCastFunction`.
452   mutable Data data_;
453   Call call_{&Traits::uninitCall};
454   Exec exec_{&detail::function::uninitNoop};
455
456   friend Traits;
457   friend Function<typename Traits::ConstSignature> folly::constCastFunction<>(
458       Function<typename Traits::NonConstSignature>&&) noexcept;
459   friend class Function<typename Traits::OtherSignature>;
460
461   template <typename Fun>
462   Function(Fun&& fun, SmallTag) noexcept {
463     using FunT = typename std::decay<Fun>::type;
464     if (!detail::function::isNullPtrFn(fun)) {
465       ::new (static_cast<void*>(&data_.tiny)) FunT(static_cast<Fun&&>(fun));
466       call_ = &Traits::template callSmall<FunT>;
467       exec_ = &detail::function::execSmall<FunT>;
468     }
469   }
470
471   template <typename Fun>
472   Function(Fun&& fun, HeapTag) {
473     using FunT = typename std::decay<Fun>::type;
474     data_.big = new FunT(static_cast<Fun&&>(fun));
475     call_ = &Traits::template callBig<FunT>;
476     exec_ = &detail::function::execBig<FunT>;
477   }
478
479   template <typename Signature>
480   Function(Function<Signature>&& that, CoerceTag)
481       : Function(static_cast<Function<Signature>&&>(that), HeapTag{}) {}
482
483   Function(
484       Function<typename Traits::OtherSignature>&& that,
485       CoerceTag) noexcept {
486     that.exec_(Op::MOVE, &that.data_, &data_);
487     std::swap(call_, that.call_);
488     std::swap(exec_, that.exec_);
489   }
490
491  public:
492   /**
493    * Default constructor. Constructs an empty Function.
494    */
495   Function() = default;
496
497   // not copyable
498   Function(const Function&) = delete;
499
500   /**
501    * Move constructor
502    */
503   Function(Function&& that) noexcept {
504     that.exec_(Op::MOVE, &that.data_, &data_);
505     std::swap(call_, that.call_);
506     std::swap(exec_, that.exec_);
507   }
508
509   /**
510    * Constructs an empty `Function`.
511    */
512   /* implicit */ Function(std::nullptr_t) noexcept {}
513
514   /**
515    * Constructs a new `Function` from any callable object that is _not_ a
516    * `folly::Function`. This handles function pointers, pointers to static
517    * member functions, `std::reference_wrapper` objects, `std::function`
518    * objects, and arbitrary objects that implement `operator()` if the parameter
519    * signature matches (i.e. it returns an object convertible to `R` when called
520    * with `Args...`).
521    *
522    * \note `typename = ResultOf<Fun>` prevents this overload from being
523    * selected by overload resolution when `fun` is not a compatible function.
524    *
525    * \note The noexcept requires some explanation. IsSmall is true when the
526    * decayed type fits within the internal buffer and is noexcept-movable. But
527    * this ctor might copy, not move. What we need here, if this ctor does a
528    * copy, is that this ctor be noexcept when the copy is noexcept. That is not
529    * checked in IsSmall, and shouldn't be, because once the Function is
530    * constructed, the contained object is never copied. This check is for this
531    * ctor only, in the case that this ctor does a copy.
532    */
533   template <
534       typename Fun,
535       typename FunT = detail::function::DecayIfConstructible<Fun>,
536       typename = typename Traits::template ResultOf<Fun>>
537   /* implicit */ Function(Fun&& fun) noexcept(
538       IsSmall<Fun>::value && noexcept(FunT(std::declval<Fun>())))
539       : Function(static_cast<Fun&&>(fun), IsSmall<Fun>{}) {}
540
541   /**
542    * For move-constructing from a `folly::Function<X(Ys...) [const?]>`.
543    * For a `Function` with a `const` function type, the object must be
544    * callable from a `const`-reference, i.e. implement `operator() const`.
545    * For a `Function` with a non-`const` function type, the object will
546    * be called from a non-const reference, which means that it will execute
547    * a non-const `operator()` if it is defined, and falls back to
548    * `operator() const` otherwise.
549    */
550   template <
551       typename Signature,
552       typename = typename Traits::template ResultOf<Function<Signature>>>
553   Function(Function<Signature>&& that) noexcept(
554       noexcept(Function(std::move(that), CoerceTag{})))
555       : Function(std::move(that), CoerceTag{}) {}
556
557   /**
558    * If `ptr` is null, constructs an empty `Function`. Otherwise,
559    * this constructor is equivalent to `Function(std::mem_fn(ptr))`.
560    */
561   template <
562       typename Member,
563       typename Class,
564       // Prevent this overload from being selected when `ptr` is not a
565       // compatible member function pointer.
566       typename = decltype(Function(std::mem_fn((Member Class::*)0)))>
567   /* implicit */ Function(Member Class::*ptr) noexcept {
568     if (ptr) {
569       *this = std::mem_fn(ptr);
570     }
571   }
572
573   ~Function() {
574     exec_(Op::NUKE, &data_, nullptr);
575   }
576
577   Function& operator=(const Function&) = delete;
578
579   /**
580    * Move assignment operator
581    */
582   Function& operator=(Function&& that) noexcept {
583     if (&that != this) {
584       // Q: Why is is safe to destroy and reconstruct this object in place?
585       // A: Two reasons: First, `Function` is a final class, so in doing this
586       //    we aren't slicing off any derived parts. And second, the move
587       //    operation is guaranteed not to throw so we always leave the object
588       //    in a valid state.
589       this->~Function();
590       ::new (this) Function(std::move(that));
591     }
592     return *this;
593   }
594
595   /**
596    * Assigns a callable object to this `Function`. If the operation fails,
597    * `*this` is left unmodified.
598    *
599    * \note `typename = ResultOf<Fun>` prevents this overload from being
600    * selected by overload resolution when `fun` is not a compatible function.
601    */
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.
609       this->~Function();
610       ::new (this) Function(static_cast<Fun&&>(fun));
611     } else {
612       // Construct a temporary and (nothrow) swap.
613       Function(static_cast<Fun&&>(fun)).swap(*this);
614     }
615     return *this;
616   }
617
618   /**
619    * For assigning from a `Function<X(Ys..) [const?]>`.
620    */
621   template <
622       typename Signature,
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)));
627   }
628
629   /**
630    * Clears this `Function`.
631    */
632   Function& operator=(std::nullptr_t) noexcept {
633     return (*this = Function());
634   }
635
636   /**
637    * If `ptr` is null, clears this `Function`. Otherwise, this assignment
638    * operator is equivalent to `*this = std::mem_fn(ptr)`.
639    */
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());
646   }
647
648   /**
649    * Call the wrapped callable object with the specified arguments.
650    */
651   using Traits::operator();
652
653   /**
654    * Exchanges the callable objects of `*this` and `that`.
655    */
656   void swap(Function& that) noexcept {
657     std::swap(*this, that);
658   }
659
660   /**
661    * Returns `true` if this `Function` contains a callable, i.e. is
662    * non-empty.
663    */
664   explicit operator bool() const noexcept {
665     return exec_(Op::FULL, nullptr, nullptr);
666   }
667
668   /**
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`
672    * object itself.
673    */
674   bool hasAllocatedMemory() const noexcept {
675     return exec_(Op::HEAP, nullptr, nullptr);
676   }
677
678   using typename Traits::SharedProxy;
679
680   /**
681    * Move this `Function` into a copyable callable object, of which all copies
682    * share the state.
683    */
684   SharedProxy asSharedProxy() && {
685     return SharedProxy{std::move(*this)};
686   }
687
688   /**
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.
692    */
693   std::function<typename Traits::NonConstSignature> asStdFunction() && {
694     return std::move(*this).asSharedProxy();
695   }
696 };
697 FOLLY_POP_WARNING
698
699 template <typename FunctionType>
700 void swap(Function<FunctionType>& lhs, Function<FunctionType>& rhs) noexcept {
701   lhs.swap(rhs);
702 }
703
704 template <typename FunctionType>
705 bool operator==(const Function<FunctionType>& fn, std::nullptr_t) {
706   return !fn;
707 }
708
709 template <typename FunctionType>
710 bool operator==(std::nullptr_t, const Function<FunctionType>& fn) {
711   return !fn;
712 }
713
714 template <typename FunctionType>
715 bool operator!=(const Function<FunctionType>& fn, std::nullptr_t) {
716   return !(fn == nullptr);
717 }
718
719 template <typename FunctionType>
720 bool operator!=(std::nullptr_t, const Function<FunctionType>& fn) {
721   return !(nullptr == fn);
722 }
723
724 /**
725  * NOTE: See detailed note about `constCastFunction` at the top of the file.
726  * This is potentially dangerous and requires the equivalent of a `const_cast`.
727  */
728 template <typename ReturnType, typename... Args>
729 Function<ReturnType(Args...) const> constCastFunction(
730     Function<ReturnType(Args...)>&& that) noexcept {
731   return Function<ReturnType(Args...) const>{std::move(that),
732                                              detail::function::CoerceTag{}};
733 }
734
735 template <typename ReturnType, typename... Args>
736 Function<ReturnType(Args...) const> constCastFunction(
737     Function<ReturnType(Args...) const>&& that) noexcept {
738   return std::move(that);
739 }
740
741 /**
742  * @class FunctionRef
743  *
744  * @brief A reference wrapper for callable objects
745  *
746  * FunctionRef is similar to std::reference_wrapper, but the template parameter
747  * is the function signature type rather than the type of the referenced object.
748  * A folly::FunctionRef is cheap to construct as it contains only a pointer to
749  * the referenced callable and a pointer to a function which invokes the
750  * callable.
751  *
752  * The user of FunctionRef must be aware of the reference semantics: storing a
753  * copy of a FunctionRef is potentially dangerous and should be avoided unless
754  * the referenced object definitely outlives the FunctionRef object. Thus any
755  * function that accepts a FunctionRef parameter should only use it to invoke
756  * the referenced function and not store a copy of it. Knowing that FunctionRef
757  * itself has reference semantics, it is generally okay to use it to reference
758  * lambdas that capture by reference.
759  */
760
761 template <typename FunctionType>
762 class FunctionRef;
763
764 template <typename ReturnType, typename... Args>
765 class FunctionRef<ReturnType(Args...)> final {
766   using Call = ReturnType (*)(void*, Args&&...);
767
768   void* object_{nullptr};
769   Call call_{&FunctionRef::uninitCall};
770
771   static ReturnType uninitCall(void*, Args&&...) {
772     throw std::bad_function_call();
773   }
774
775   template <typename Fun>
776   static ReturnType call(void* object, Args&&... args) {
777     return static_cast<ReturnType>(detail::function::invoke(
778         *static_cast<Fun*>(object), static_cast<Args&&>(args)...));
779   }
780
781  public:
782   /**
783    * Default constructor. Constructs an empty FunctionRef.
784    *
785    * Invoking it will throw std::bad_function_call.
786    */
787   FunctionRef() = default;
788
789   /**
790    * Construct a FunctionRef from a reference to a callable object.
791    */
792   template <typename Fun>
793   /* implicit */ FunctionRef(Fun&& fun) noexcept {
794     using ReferencedType = typename std::remove_reference<Fun>::type;
795
796     static_assert(
797         std::is_convertible<
798             typename std::result_of<ReferencedType&(Args && ...)>::type,
799             ReturnType>::value,
800         "FunctionRef cannot be constructed from object with "
801         "incompatible function signature");
802
803     // `Fun` may be a const type, in which case we have to do a const_cast
804     // to store the address in a `void*`. This is safe because the `void*`
805     // will be cast back to `Fun*` (which is a const pointer whenever `Fun`
806     // is a const type) inside `FunctionRef::call`
807     object_ = const_cast<void*>(static_cast<void const*>(std::addressof(fun)));
808     call_ = &FunctionRef::call<ReferencedType>;
809   }
810
811   ReturnType operator()(Args... args) const {
812     return call_(object_, static_cast<Args&&>(args)...);
813   }
814
815   explicit operator bool() const {
816     return object_;
817   }
818 };
819
820 } // namespace folly