Introducing folly::FunctionRef
[folly.git] / folly / Function.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * @author Eric Niebler (eniebler@fb.com), Sven Over (over@fb.com)
5  *
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
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
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
229 namespace folly {
230
231 template <typename FunctionType>
232 class Function;
233
234 template <typename ReturnType, typename... Args>
235 Function<ReturnType(Args...) const> constCastFunction(
236     Function<ReturnType(Args...)>&&) noexcept;
237
238 namespace detail {
239 namespace function {
240
241 enum class Op { MOVE, NUKE, FULL, HEAP };
242
243 union Data {
244   void* big;
245   std::aligned_storage<6 * sizeof(void*)>::type tiny;
246 };
247
248 template <typename Fun, typename FunT = typename std::decay<Fun>::type>
249 using IsSmall = std::integral_constant<
250     bool,
251     (sizeof(FunT) <= sizeof(Data::tiny) &&
252      // Same as is_nothrow_move_constructible, but w/ no template instantiation.
253      noexcept(FunT(std::declval<FunT&&>())))>;
254 using SmallTag = std::true_type;
255 using HeapTag = std::false_type;
256
257 struct CoerceTag {};
258
259 template <typename T>
260 bool isNullPtrFn(T* p) {
261   return p == nullptr;
262 }
263 template <typename T>
264 std::false_type isNullPtrFn(T&&) {
265   return {};
266 }
267
268 inline bool uninitNoop(Op, Data*, Data*) {
269   return false;
270 }
271
272 template <typename FunctionType>
273 struct FunctionTraits;
274
275 template <typename ReturnType, typename... Args>
276 struct FunctionTraits<ReturnType(Args...)> {
277   using Call = ReturnType (*)(Data&, Args&&...);
278   using IsConst = std::false_type;
279   using ConstSignature = ReturnType(Args...) const;
280   using NonConstSignature = ReturnType(Args...);
281   using OtherSignature = ConstSignature;
282
283   template <typename F, typename G = typename std::decay<F>::type>
284   using ResultOf = decltype(
285       static_cast<ReturnType>(std::declval<G&>()(std::declval<Args>()...)));
286
287   template <typename Fun>
288   static ReturnType callSmall(Data& p, Args&&... args) {
289     return static_cast<ReturnType>((*static_cast<Fun*>(
290         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
291   }
292
293   template <typename Fun>
294   static ReturnType callBig(Data& p, Args&&... args) {
295     return static_cast<ReturnType>(
296         (*static_cast<Fun*>(p.big))(static_cast<Args&&>(args)...));
297   }
298
299   static ReturnType uninitCall(Data&, Args&&...) {
300     throw std::bad_function_call();
301   }
302
303   ReturnType operator()(Args... args) {
304     auto& fn = *static_cast<Function<ReturnType(Args...)>*>(this);
305     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
306   }
307
308   struct SharedFunctionImpl {
309     std::shared_ptr<Function<ReturnType(Args...)>> sp_;
310     ReturnType operator()(Args&&... args) const {
311       return (*sp_)(static_cast<Args&&>(args)...);
312     }
313   };
314 };
315
316 template <typename ReturnType, typename... Args>
317 struct FunctionTraits<ReturnType(Args...) const> {
318   using Call = ReturnType (*)(Data&, Args&&...);
319   using IsConst = std::true_type;
320   using ConstSignature = ReturnType(Args...) const;
321   using NonConstSignature = ReturnType(Args...);
322   using OtherSignature = NonConstSignature;
323
324   template <typename F, typename G = typename std::decay<F>::type>
325   using ResultOf = decltype(static_cast<ReturnType>(
326       std::declval<const G&>()(std::declval<Args>()...)));
327
328   template <typename Fun>
329   static ReturnType callSmall(Data& p, Args&&... args) {
330     return static_cast<ReturnType>((*static_cast<const Fun*>(
331         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
332   }
333
334   template <typename Fun>
335   static ReturnType callBig(Data& p, Args&&... args) {
336     return static_cast<ReturnType>(
337         (*static_cast<const Fun*>(p.big))(static_cast<Args&&>(args)...));
338   }
339
340   static ReturnType uninitCall(Data&, Args&&...) {
341     throw std::bad_function_call();
342   }
343
344   ReturnType operator()(Args... args) const {
345     auto& fn = *static_cast<const Function<ReturnType(Args...) const>*>(this);
346     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
347   }
348
349   struct SharedFunctionImpl {
350     std::shared_ptr<Function<ReturnType(Args...) const>> sp_;
351     ReturnType operator()(Args&&... args) const {
352       return (*sp_)(static_cast<Args&&>(args)...);
353     }
354   };
355 };
356
357 template <typename Fun>
358 bool execSmall(Op o, Data* src, Data* dst) {
359   switch (o) {
360     case Op::MOVE:
361       ::new (static_cast<void*>(&dst->tiny))
362           Fun(std::move(*static_cast<Fun*>(static_cast<void*>(&src->tiny))));
363       FOLLY_FALLTHROUGH;
364     case Op::NUKE:
365       static_cast<Fun*>(static_cast<void*>(&src->tiny))->~Fun();
366       break;
367     case Op::FULL:
368       return true;
369     case Op::HEAP:
370       break;
371   }
372   return false;
373 }
374
375 template <typename Fun>
376 bool execBig(Op o, Data* src, Data* dst) {
377   switch (o) {
378     case Op::MOVE:
379       dst->big = src->big;
380       src->big = nullptr;
381       break;
382     case Op::NUKE:
383       delete static_cast<Fun*>(src->big);
384       break;
385     case Op::FULL:
386     case Op::HEAP:
387       break;
388   }
389   return true;
390 }
391
392 // Invoke helper
393 template <typename F, typename... Args>
394 inline auto invoke(F&& f, Args&&... args)
395     -> decltype(std::forward<F>(f)(std::forward<Args>(args)...)) {
396   return std::forward<F>(f)(std::forward<Args>(args)...);
397 }
398
399 template <typename M, typename C, typename... Args>
400 inline auto invoke(M(C::*d), Args&&... args)
401     -> decltype(std::mem_fn(d)(std::forward<Args>(args)...)) {
402   return std::mem_fn(d)(std::forward<Args>(args)...);
403 }
404
405 } // namespace function
406 } // namespace detail
407
408 FOLLY_PUSH_WARNING
409 FOLLY_MSVC_DISABLE_WARNING(4521) // Multiple copy constructors
410 FOLLY_MSVC_DISABLE_WARNING(4522) // Multiple assignment operators
411 template <typename FunctionType>
412 class Function final : private detail::function::FunctionTraits<FunctionType> {
413   // These utility types are defined outside of the template to reduce
414   // the number of instantiations, and then imported in the class
415   // namespace for convenience.
416   using Data = detail::function::Data;
417   using Op = detail::function::Op;
418   using SmallTag = detail::function::SmallTag;
419   using HeapTag = detail::function::HeapTag;
420   using CoerceTag = detail::function::CoerceTag;
421
422   using Traits = detail::function::FunctionTraits<FunctionType>;
423   using Call = typename Traits::Call;
424   using Exec = bool (*)(Op, Data*, Data*);
425
426   template <typename Fun>
427   using IsSmall = detail::function::IsSmall<Fun>;
428
429   using OtherSignature = typename Traits::OtherSignature;
430
431   // The `data_` member is mutable to allow `constCastFunction` to work without
432   // invoking undefined behavior. Const-correctness is only violated when
433   // `FunctionType` is a const function type (e.g., `int() const`) and `*this`
434   // is the result of calling `constCastFunction`.
435   mutable Data data_;
436   Call call_{&Traits::uninitCall};
437   Exec exec_{&detail::function::uninitNoop};
438
439   friend Traits;
440   friend Function<typename Traits::ConstSignature> folly::constCastFunction<>(
441       Function<typename Traits::NonConstSignature>&&) noexcept;
442   friend class Function<OtherSignature>;
443
444   template <typename Fun>
445   Function(Fun&& fun, SmallTag) noexcept {
446     using FunT = typename std::decay<Fun>::type;
447     if (!detail::function::isNullPtrFn(fun)) {
448       ::new (static_cast<void*>(&data_.tiny)) FunT(static_cast<Fun&&>(fun));
449       call_ = &Traits::template callSmall<FunT>;
450       exec_ = &detail::function::execSmall<FunT>;
451     }
452   }
453
454   template <typename Fun>
455   Function(Fun&& fun, HeapTag) {
456     using FunT = typename std::decay<Fun>::type;
457     data_.big = new FunT(static_cast<Fun&&>(fun));
458     call_ = &Traits::template callBig<FunT>;
459     exec_ = &detail::function::execBig<FunT>;
460   }
461
462   Function(Function<OtherSignature>&& that, CoerceTag) noexcept {
463     that.exec_(Op::MOVE, &that.data_, &data_);
464     std::swap(call_, that.call_);
465     std::swap(exec_, that.exec_);
466   }
467
468  public:
469   /**
470    * Default constructor. Constructs an empty Function.
471    */
472   Function() = default;
473
474   // not copyable
475   // NOTE: Deleting the non-const copy constructor is unusual but necessary to
476   // prevent copies from non-const `Function` object from selecting the
477   // perfect forwarding implicit converting constructor below
478   // (i.e., `template <typename Fun> Function(Fun&&)`).
479   Function(Function&) = delete;
480   Function(const Function&) = delete;
481   Function(const Function&&) = delete;
482
483   /**
484    * Move constructor
485    */
486   Function(Function&& that) noexcept {
487     that.exec_(Op::MOVE, &that.data_, &data_);
488     std::swap(call_, that.call_);
489     std::swap(exec_, that.exec_);
490   }
491
492   /**
493    * Constructs an empty `Function`.
494    */
495   /* implicit */ Function(std::nullptr_t) noexcept {}
496
497   /**
498    * Constructs a new `Function` from any callable object. This
499    * handles function pointers, pointers to static member functions,
500    * `std::reference_wrapper` objects, `std::function` objects, and arbitrary
501    * objects that implement `operator()` if the parameter signature
502    * matches (i.e. it returns R when called with Args...).
503    * For a `Function` with a const function type, the object must be
504    * callable from a const-reference, i.e. implement `operator() const`.
505    * For a `Function` with a non-const function type, the object will
506    * be called from a non-const reference, which means that it will execute
507    * a non-const `operator()` if it is defined, and falls back to
508    * `operator() const` otherwise.
509    *
510    * \note `typename = ResultOf<Fun>` prevents this overload from being
511    * selected by overload resolution when `fun` is not a compatible function.
512    */
513   template <class Fun, typename = typename Traits::template ResultOf<Fun>>
514   /* implicit */ Function(Fun&& fun) noexcept(IsSmall<Fun>::value)
515       : Function(static_cast<Fun&&>(fun), IsSmall<Fun>{}) {}
516
517   /**
518    * For moving a `Function<X(Ys..) const>` into a `Function<X(Ys...)>`.
519    */
520   template <
521       bool Const = Traits::IsConst::value,
522       typename std::enable_if<!Const, int>::type = 0>
523   Function(Function<OtherSignature>&& that) noexcept
524       : Function(std::move(that), CoerceTag{}) {}
525
526   /**
527    * If `ptr` is null, constructs an empty `Function`. Otherwise,
528    * this constructor is equivalent to `Function(std::mem_fn(ptr))`.
529    */
530   template <
531       typename Member,
532       typename Class,
533       // Prevent this overload from being selected when `ptr` is not a
534       // compatible member function pointer.
535       typename = decltype(Function(std::mem_fn((Member Class::*)0)))>
536   /* implicit */ Function(Member Class::*ptr) noexcept {
537     if (ptr) {
538       *this = std::mem_fn(ptr);
539     }
540   }
541
542   ~Function() {
543     exec_(Op::NUKE, &data_, nullptr);
544   }
545
546   Function& operator=(Function&) = delete;
547   Function& operator=(const Function&) = delete;
548
549   /**
550    * Move assignment operator
551    */
552   Function& operator=(Function&& that) noexcept {
553     if (&that != this) {
554       // Q: Why is is safe to destroy and reconstruct this object in place?
555       // A: Two reasons: First, `Function` is a final class, so in doing this
556       //    we aren't slicing off any derived parts. And second, the move
557       //    operation is guaranteed not to throw so we always leave the object
558       //    in a valid state.
559       this->~Function();
560       ::new (this) Function(std::move(that));
561     }
562     return *this;
563   }
564
565   /**
566    * Assigns a callable object to this `Function`. If the operation fails,
567    * `*this` is left unmodified.
568    *
569    * \note `typename = ResultOf<Fun>` prevents this overload from being
570    * selected by overload resolution when `fun` is not a compatible function.
571    */
572   template <class Fun, typename = typename Traits::template ResultOf<Fun>>
573   Function& operator=(Fun&& fun) noexcept(
574       noexcept(/* implicit */ Function(std::declval<Fun>()))) {
575     // Doing this in place is more efficient when we can do so safely.
576     if (noexcept(/* implicit */ Function(std::declval<Fun>()))) {
577       // Q: Why is is safe to destroy and reconstruct this object in place?
578       // A: See the explanation in the move assignment operator.
579       this->~Function();
580       ::new (this) Function(static_cast<Fun&&>(fun));
581     } else {
582       // Construct a temporary and (nothrow) swap.
583       Function(static_cast<Fun&&>(fun)).swap(*this);
584     }
585     return *this;
586   }
587
588   /**
589    * Clears this `Function`.
590    */
591   Function& operator=(std::nullptr_t) noexcept {
592     return (*this = Function());
593   }
594
595   /**
596    * If `ptr` is null, clears this `Function`. Otherwise, this assignment
597    * operator is equivalent to `*this = std::mem_fn(ptr)`.
598    */
599   template <typename Member, typename Class>
600   auto operator=(Member Class::*ptr) noexcept
601       // Prevent this overload from being selected when `ptr` is not a
602       // compatible member function pointer.
603       -> decltype(operator=(std::mem_fn(ptr))) {
604     return ptr ? (*this = std::mem_fn(ptr)) : (*this = Function());
605   }
606
607   /**
608    * Call the wrapped callable object with the specified arguments.
609    */
610   using Traits::operator();
611
612   /**
613    * Exchanges the callable objects of `*this` and `that`.
614    */
615   void swap(Function& that) noexcept {
616     std::swap(*this, that);
617   }
618
619   /**
620    * Returns `true` if this `Function` contains a callable, i.e. is
621    * non-empty.
622    */
623   explicit operator bool() const noexcept {
624     return exec_(Op::FULL, nullptr, nullptr);
625   }
626
627   /**
628    * Returns `true` if this `Function` stores the callable on the
629    * heap. If `false` is returned, there has been no additional memory
630    * allocation and the callable is stored inside the `Function`
631    * object itself.
632    */
633   bool hasAllocatedMemory() const noexcept {
634     return exec_(Op::HEAP, nullptr, nullptr);
635   }
636
637   /**
638    * Construct a `std::function` by moving in the contents of this `Function`.
639    * Note that the returned `std::function` will share its state (i.e. captured
640    * data) across all copies you make of it, so be very careful when copying.
641    */
642   std::function<typename Traits::NonConstSignature> asStdFunction() && {
643     using Impl = typename Traits::SharedFunctionImpl;
644     return Impl{std::make_shared<Function>(std::move(*this))};
645   }
646 };
647 FOLLY_POP_WARNING
648
649 template <typename FunctionType>
650 void swap(Function<FunctionType>& lhs, Function<FunctionType>& rhs) noexcept {
651   lhs.swap(rhs);
652 }
653
654 template <typename FunctionType>
655 bool operator==(const Function<FunctionType>& fn, std::nullptr_t) {
656   return !fn;
657 }
658
659 template <typename FunctionType>
660 bool operator==(std::nullptr_t, const Function<FunctionType>& fn) {
661   return !fn;
662 }
663
664 template <typename FunctionType>
665 bool operator!=(const Function<FunctionType>& fn, std::nullptr_t) {
666   return !(fn == nullptr);
667 }
668
669 template <typename FunctionType>
670 bool operator!=(std::nullptr_t, const Function<FunctionType>& fn) {
671   return !(nullptr == fn);
672 }
673
674 /**
675  * NOTE: See detailed note about `constCastFunction` at the top of the file.
676  * This is potentially dangerous and requires the equivalent of a `const_cast`.
677  */
678 template <typename ReturnType, typename... Args>
679 Function<ReturnType(Args...) const> constCastFunction(
680     Function<ReturnType(Args...)>&& that) noexcept {
681   return Function<ReturnType(Args...) const>{std::move(that),
682                                              detail::function::CoerceTag{}};
683 }
684
685 template <typename ReturnType, typename... Args>
686 Function<ReturnType(Args...) const> constCastFunction(
687     Function<ReturnType(Args...) const>&& that) noexcept {
688   return std::move(that);
689 }
690
691 /**
692  * @class FunctionRef
693  *
694  * @brief A reference wrapper for callable objects
695  *
696  * FunctionRef is similar to std::reference_wrapper, but the template parameter
697  * is the function signature type rather than the type of the referenced object.
698  * A folly::FunctionRef is cheap to construct as it contains only a pointer to
699  * the referenced callable and a pointer to a function which invokes the
700  * callable.
701  *
702  * The user of FunctionRef must be aware of the reference semantics: storing a
703  * copy of a FunctionRef is potentially dangerous and should be avoided unless
704  * the referenced object definitely outlives the FunctionRef object. Thus any
705  * function that accepts a FunctionRef parameter should only use it to invoke
706  * the referenced function and not store a copy of it. Knowing that FunctionRef
707  * itself has reference semantics, it is generally okay to use it to reference
708  * lambdas that capture by reference.
709  */
710
711 template <typename FunctionType>
712 class FunctionRef;
713
714 template <typename ReturnType, typename... Args>
715 class FunctionRef<ReturnType(Args...)> final {
716   using Call = ReturnType (*)(void*, Args&&...);
717
718   void* object_{nullptr};
719   Call call_{&FunctionRef::uninitCall};
720
721   static ReturnType uninitCall(void*, Args&&...) {
722     throw std::bad_function_call();
723   }
724
725   template <typename Fun>
726   static ReturnType call(void* object, Args&&... args) {
727     return static_cast<ReturnType>(detail::function::invoke(
728         *static_cast<Fun*>(object), static_cast<Args&&>(args)...));
729   }
730
731  public:
732   /**
733    * Default constructor. Constructs an empty FunctionRef.
734    *
735    * Invoking it will throw std::bad_function_call.
736    */
737   FunctionRef() = default;
738
739   /**
740    * Construct a FunctionRef from a reference to a callable object.
741    */
742   template <typename Fun>
743   /* implicit */ FunctionRef(Fun&& fun) noexcept {
744     using ReferencedType = typename std::remove_reference<Fun>::type;
745
746     static_assert(
747         std::is_convertible<
748             typename std::result_of<ReferencedType&(Args && ...)>::type,
749             ReturnType>::value,
750         "FunctionRef cannot be constructed from object with "
751         "incompatible function signature");
752
753     // `Fun` may be a const type, in which case we have to do a const_cast
754     // to store the address in a `void*`. This is safe because the `void*`
755     // will be cast back to `Fun*` (which is a const pointer whenever `Fun`
756     // is a const type) inside `FunctionRef::call`
757     object_ = const_cast<void*>(static_cast<void const*>(std::addressof(fun)));
758     call_ = &FunctionRef::call<ReferencedType>;
759   }
760
761   ReturnType operator()(Args... args) const {
762     return call_(object_, static_cast<Args&&>(args)...);
763   }
764 };
765
766 } // namespace folly