Log (de)compression bytes
[folly.git] / folly / Poly.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 // TODO: [x] "cast" from Poly<C&> to Poly<C&&>
18 // TODO: [ ] copy/move from Poly<C&>/Poly<C&&> to Poly<C>
19 // TODO: [ ] copy-on-write?
20 // TODO: [ ] down- and cross-casting? (Possible?)
21 // TODO: [ ] shared ownership? (Dubious.)
22 // TODO: [ ] can games be played with making the VTable a member of a struct
23 //           with strange alignment such that the address of the VTable can
24 //           be used to tell whether the object is stored in-situ or not?
25
26 #pragma once
27
28 #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 5
29 #error Folly.Poly requires gcc-5 or greater
30 #endif
31
32 #include <cassert>
33 #include <new>
34 #include <type_traits>
35 #include <typeinfo>
36 #include <utility>
37
38 #include <folly/CPortability.h>
39 #include <folly/CppAttributes.h>
40 #include <folly/Traits.h>
41 #include <folly/detail/TypeList.h>
42 #include <folly/lang/Assume.h>
43
44 #if !defined(__cpp_inline_variables)
45 #define FOLLY_INLINE_CONSTEXPR constexpr
46 #else
47 #define FOLLY_INLINE_CONSTEXPR inline constexpr
48 #endif
49
50 #include <folly/detail/PolyDetail.h>
51
52 namespace folly {
53 template <class I>
54 struct Poly;
55
56 /**
57  * Within the definition of interface `I`, `PolySelf<Base>` is an alias for
58  * the instance of `Poly` that is currently being instantiated. It is
59  * one of: `Poly<J>`, `Poly<J&&>`, `Poly<J&>`, or `Poly<J const&>`; where
60  * `J` is either `I` or some interface that extends `I`.
61  *
62  * It can be used within interface definitions to declare members that accept
63  * other `Poly` objects of the same type as `*this`.
64  *
65  * The first parameter may optionally be cv- and/or reference-qualified, in
66  * which case, the qualification is applies to the type of the interface in the
67  * resulting `Poly<>` instance. The second template parameter controls whether
68  * or not the interface is decayed before the cv-ref qualifiers of the first
69  * argument are applied. For example, given the following:
70  *
71  *     struct Foo {
72  *       template <class Base>
73  *       struct Interface : Base {
74  *         using A = PolySelf<Base>;
75  *         using B = PolySelf<Base &>;
76  *         using C = PolySelf<Base const &>;
77  *         using X = PolySelf<Base, PolyDecay>;
78  *         using Y = PolySelf<Base &, PolyDecay>;
79  *         using Z = PolySelf<Base const &, PolyDecay>;
80  *       };
81  *       // ...
82  *     };
83  *     struct Bar : PolyExtends<Foo> {
84  *       // ...
85  *     };
86  *
87  * Then for `Poly<Bar>`, the typedefs are aliases for the following types:
88  * - `A` is `Poly<Bar>`
89  * - `B` is `Poly<Bar &>`
90  * - `C` is `Poly<Bar const &>`
91  * - `X` is `Poly<Bar>`
92  * - `Y` is `Poly<Bar &>`
93  * - `Z` is `Poly<Bar const &>`
94  *
95  * And for `Poly<Bar &>`, the typedefs are aliases for the following types:
96  * - `A` is `Poly<Bar &>`
97  * - `B` is `Poly<Bar &>`
98  * - `C` is `Poly<Bar &>`
99  * - `X` is `Poly<Bar>`
100  * - `Y` is `Poly<Bar &>`
101  * - `Z` is `Poly<Bar const &>`
102  */
103 template <
104     class Node,
105     class Tfx = detail::MetaIdentity,
106     class Access = detail::PolyAccess>
107 using PolySelf = decltype(Access::template self_<Node, Tfx>());
108
109 /**
110  * When used in conjunction with `PolySelf`, controls how to construct `Poly`
111  * types related to the one currently being instantiated.
112  *
113  * \sa PolySelf
114  */
115 using PolyDecay = detail::MetaQuote<std::decay_t>;
116
117 #if !defined(__cpp_template_auto)
118
119 /**
120  * Use `FOLLY_POLY_MEMBERS(MEMS...)` on pre-C++17 compilers to specify a
121  * comma-separated list of member function bindings.
122  *
123  * For example:
124  *
125  *     struct IFooBar {
126  *       template <class Base>
127  *       struct Interface : Base {
128  *         int foo() const { return folly::poly_call<0>(*this); }
129  *         void bar() { folly::poly_call<1>(*this); }
130  *       };
131  *       template <class T>
132  *       using Members = FOLLY_POLY_MEMBERS(&T::foo, &T::bar);
133  *     };
134  */
135 #define FOLLY_POLY_MEMBERS(...)                     \
136   typename decltype(::folly::detail::deduceMembers( \
137       __VA_ARGS__))::template Members<__VA_ARGS__>
138
139 /**
140  * Use `FOLLY_POLY_MEMBER(SIG, MEM)` on pre-C++17 compilers to specify a member
141  * function binding that needs to be disambiguated because of overloads. `SIG`
142  * should the (possibly const-qualified) signature of the `MEM` member function
143  * pointer.
144  *
145  * For example:
146  *
147  *     struct IFoo {
148  *       template <class Base> struct Interface : Base {
149  *         int foo() const { return folly::poly_call<0>(*this); }
150  *       };
151  *       template <class T> using Members = FOLLY_POLY_MEMBERS(
152  *         // This works even if T::foo is overloaded:
153  *         FOLLY_POLY_MEMBER(int()const, &T::foo)
154  *       );
155  *     };
156  */
157 #define FOLLY_POLY_MEMBER(SIG, MEM) \
158   ::folly::detail::MemberDef<       \
159       ::folly::detail::Member<decltype(::folly::sig<SIG>(MEM)), MEM>>::value
160
161 /**
162  * A list of member function bindings.
163  */
164 template <class... Ts>
165 using PolyMembers = detail::TypeList<Ts...>;
166
167 #else
168 #define FOLLY_POLY_MEMBER(SIG, MEM) ::folly::sig<SIG>(MEM)
169 #define FOLLY_POLY_MEMBERS(...) ::folly::PolyMembers<__VA_ARGS__>
170
171 template <auto... Ps>
172 struct PolyMembers {};
173
174 #endif
175
176 /**
177  * Exception type that is thrown on invalid access of an empty `Poly` object.
178  */
179 struct FOLLY_EXPORT BadPolyAccess : std::exception {
180   BadPolyAccess() = default;
181   char const* what() const noexcept override {
182     return "BadPolyAccess";
183   }
184 };
185
186 /**
187  * Exception type that is thrown when attempting to extract from a `Poly` a
188  * value of the wrong type.
189  */
190 struct FOLLY_EXPORT BadPolyCast : std::bad_cast {
191   BadPolyCast() = default;
192   char const* what() const noexcept override {
193     return "BadPolyCast";
194   }
195 };
196
197 /**
198  * Used in the definition of a `Poly` interface to say that the current
199  * interface is an extension of a set of zero or more interfaces.
200  *
201  * Example:
202  *
203  *   struct IFoo {
204  *     template <class Base> struct Interface : Base {
205  *       void foo() { folly::poly_call<0>(*this); }
206  *     };
207  *     template <class T> using Members = FOLLY_POLY_MEMBERS(&T::foo);
208  *   }
209  *   struct IBar : PolyExtends<IFoo> {
210  *     template <class Base> struct Interface : Base {
211  *       void bar(int i) { folly::poly_call<0>(*this, i); }
212  *     };
213  *     template <class T> using Members = FOLLY_POLY_MEMBERS(&T::bar);
214  *   }
215  */
216 template <class... I>
217 struct PolyExtends : virtual I... {
218   using Subsumptions = detail::TypeList<I...>;
219
220   template <class Base>
221   struct Interface : Base {
222     Interface() = default;
223     using Base::Base;
224   };
225
226   template <class...>
227   using Members = PolyMembers<>;
228 };
229
230 ////////////////////////////////////////////////////////////////////////////////
231 /**
232  * Call the N-th member of the currently-being-defined interface. When the
233  * first parameter is an object of type `PolySelf<Base>` (as opposed to `*this`)
234  * you must explicitly specify which interface through which to dispatch.
235  * For instance:
236  *
237  *     struct IAddable {
238  *       template <class Base>
239  *       struct Interface : Base {
240  *         friend PolySelf<Base, Decay>
241  *         operator+(PolySelf<Base> const& a, PolySelf<Base> const& b) {
242  *           return folly::poly_call<0, IAddable>(a, b);
243  *         }
244  *       };
245  *       template <class T>
246  *       static auto plus_(T const& a, T const& b) -> decltype(a + b) {
247  *         return a + b;
248  *       }
249  *       template <class T>
250  *       using Members = FOLLY_POLY_MEMBERS(&plus_<std::decay_t<T>>);
251  *     };
252  *
253  * \sa PolySelf
254  */
255 template <std::size_t N, typename This, typename... As>
256 auto poly_call(This&& _this, As&&... as)
257     -> decltype(detail::PolyAccess::call<N>(
258         static_cast<This&&>(_this),
259         static_cast<As&&>(as)...)) {
260   return detail::PolyAccess::call<N>(
261       static_cast<This&&>(_this), static_cast<As&&>(as)...);
262 }
263
264 /// \overload
265 template <std::size_t N, class I, class Tail, typename... As>
266 decltype(auto) poly_call(detail::PolyNode<I, Tail>&& _this, As&&... as) {
267   using This = detail::InterfaceOf<I, detail::PolyNode<I, Tail>>;
268   return detail::PolyAccess::call<N>(
269       static_cast<This&&>(_this), static_cast<As&&>(as)...);
270 }
271
272 /// \overload
273 template <std::size_t N, class I, class Tail, typename... As>
274 decltype(auto) poly_call(detail::PolyNode<I, Tail>& _this, As&&... as) {
275   using This = detail::InterfaceOf<I, detail::PolyNode<I, Tail>>;
276   return detail::PolyAccess::call<N>(
277       static_cast<This&>(_this), static_cast<As&&>(as)...);
278 }
279
280 /// \overload
281 template <std::size_t N, class I, class Tail, typename... As>
282 decltype(auto) poly_call(detail::PolyNode<I, Tail> const& _this, As&&... as) {
283   using This = detail::InterfaceOf<I, detail::PolyNode<I, Tail>>;
284   return detail::PolyAccess::call<N>(
285       static_cast<This const&>(_this), static_cast<As&&>(as)...);
286 }
287
288 /// \overload
289 template <
290     std::size_t N,
291     class I,
292     class Poly,
293     typename... As,
294     std::enable_if_t<detail::IsPoly<Poly>::value, int> = 0>
295 auto poly_call(Poly&& _this, As&&... as) -> decltype(poly_call<N, I>(
296     static_cast<Poly&&>(_this).get(),
297     static_cast<As&&>(as)...)) {
298   return poly_call<N, I>(
299       static_cast<Poly&&>(_this).get(), static_cast<As&&>(as)...);
300 }
301
302 /// \cond
303 /// \overload
304 template <std::size_t N, class I, typename... As>
305 [[noreturn]] detail::Bottom poly_call(detail::ArchetypeBase const&, As&&...) {
306   assume_unreachable();
307 }
308 /// \endcond
309
310 ////////////////////////////////////////////////////////////////////////////////
311 /**
312  * Try to cast the `Poly` object to the requested type. If the `Poly` stores an
313  * object of that type, return a reference to the object; otherwise, throw an
314  * exception.
315  * \tparam T The (unqualified) type to which to cast the `Poly` object.
316  * \tparam Poly The type of the `Poly` object.
317  * \param that The `Poly` object to be cast.
318  * \return A reference to the `T` object stored in or refered to by `that`.
319  * \throw BadPolyAccess if `that` is empty.
320  * \throw BadPolyCast if `that` does not store or refer to an object of type
321  *        `T`.
322  */
323 template <class T, class I>
324 detail::AddCvrefOf<T, I>&& poly_cast(detail::PolyRoot<I>&& that) {
325   return detail::PolyAccess::cast<T>(std::move(that));
326 }
327
328 /// \overload
329 template <class T, class I>
330 detail::AddCvrefOf<T, I>& poly_cast(detail::PolyRoot<I>& that) {
331   return detail::PolyAccess::cast<T>(that);
332 }
333
334 /// \overload
335 template <class T, class I>
336 detail::AddCvrefOf<T, I> const& poly_cast(detail::PolyRoot<I> const& that) {
337   return detail::PolyAccess::cast<T>(that);
338 }
339
340 /// \cond
341 /// \overload
342 template <class T, class I>
343 [[noreturn]] detail::AddCvrefOf<T, I>&& poly_cast(detail::ArchetypeRoot<I>&&) {
344   assume_unreachable();
345 }
346
347 /// \overload
348 template <class T, class I>
349 [[noreturn]] detail::AddCvrefOf<T, I>& poly_cast(detail::ArchetypeRoot<I>&) {
350   assume_unreachable();
351 }
352
353 /// \overload
354 template <class T, class I>
355 [[noreturn]] detail::AddCvrefOf<T, I> const& poly_cast(
356     detail::ArchetypeRoot<I> const&) { assume_unreachable(); }
357 /// \endcond
358
359 /// \overload
360 template <
361     class T,
362     class Poly,
363     std::enable_if_t<detail::IsPoly<Poly>::value, int> = 0>
364 constexpr auto poly_cast(Poly&& that)
365     -> decltype(poly_cast<T>(std::declval<Poly>().get())) {
366   return poly_cast<T>(static_cast<Poly&&>(that).get());
367 }
368
369 ////////////////////////////////////////////////////////////////////////////////
370 /**
371  * Returns a reference to the `std::type_info` object corresponding to the
372  * object currently stored in `that`. If `that` is empty, returns
373  * `typeid(void)`.
374  */
375 template <class I>
376 std::type_info const& poly_type(detail::PolyRoot<I> const& that) noexcept {
377   return detail::PolyAccess::type(that);
378 }
379
380 /// \cond
381 /// \overload
382 [[noreturn]] inline std::type_info const& poly_type(
383     detail::ArchetypeBase const&) noexcept {
384   assume_unreachable();
385 }
386 /// \endcond
387
388 /// \overload
389 template <class Poly, std::enable_if_t<detail::IsPoly<Poly>::value, int> = 0>
390 constexpr auto poly_type(Poly const& that) noexcept
391     -> decltype(poly_type(that.get())) {
392   return poly_type(that.get());
393 }
394
395 ////////////////////////////////////////////////////////////////////////////////
396 /**
397  * Returns `true` if `that` is not currently storing an object; `false`,
398  * otherwise.
399  */
400 template <class I>
401 bool poly_empty(detail::PolyRoot<I> const& that) noexcept {
402   return detail::State::eEmpty == detail::PolyAccess::vtable(that)->state_;
403 }
404
405 /// \overload
406 template <class I>
407 constexpr bool poly_empty(detail::PolyRoot<I&&> const&) noexcept {
408   return false;
409 }
410
411 /// \overload
412 template <class I>
413 constexpr bool poly_empty(detail::PolyRoot<I&> const&) noexcept {
414   return false;
415 }
416
417 /// \overload
418 template <class I>
419 constexpr bool poly_empty(Poly<I&&> const&) noexcept {
420   return false;
421 }
422
423 /// \overload
424 template <class I>
425 constexpr bool poly_empty(Poly<I&> const&) noexcept {
426   return false;
427 }
428
429 /// \cond
430 [[noreturn]] inline bool poly_empty(detail::ArchetypeBase const&) noexcept {
431   assume_unreachable();
432 }
433 /// \endcond
434
435 ////////////////////////////////////////////////////////////////////////////////
436 /**
437  * Given a `Poly<I&>`, return a `Poly<I&&>`. Otherwise, when `I` is not a
438  * reference type, returns a `Poly<I>&&` when given a `Poly<I>&`, like
439  * `std::move`.
440  */
441 template <
442     class I,
443     std::enable_if_t<detail::Not<std::is_reference<I>>::value, int> = 0>
444 constexpr Poly<I>&& poly_move(detail::PolyRoot<I>& that) noexcept {
445   return static_cast<Poly<I>&&>(static_cast<Poly<I>&>(that));
446 }
447
448 /// \overload
449 template <
450     class I,
451     std::enable_if_t<detail::Not<std::is_const<I>>::value, int> = 0>
452 Poly<I&&> poly_move(detail::PolyRoot<I&> const& that) noexcept {
453   return detail::PolyAccess::move(that);
454 }
455
456 /// \overload
457 template <class I>
458 Poly<I const&> poly_move(detail::PolyRoot<I const&> const& that) noexcept {
459   return detail::PolyAccess::move(that);
460 }
461
462 /// \cond
463 /// \overload
464 [[noreturn]] inline detail::ArchetypeBase poly_move(
465     detail::ArchetypeBase const&) noexcept {
466   assume_unreachable();
467 }
468 /// \endcond
469
470 /// \overload
471 template <class Poly, std::enable_if_t<detail::IsPoly<Poly>::value, int> = 0>
472 constexpr auto poly_move(Poly& that) noexcept
473     -> decltype(poly_move(that.get())) {
474   return poly_move(that.get());
475 }
476
477 /// \cond
478 namespace detail {
479 /**
480  * The implementation for `Poly` for when the interface type is not
481  * reference-like qualified, as in `Poly<SemiRegular>`.
482  */
483 template <class I>
484 struct PolyVal : PolyImpl<I> {
485  private:
486   friend PolyAccess;
487
488   struct NoneSuch {};
489   using Copyable = std::is_copy_constructible<PolyImpl<I>>;
490   using PolyOrNonesuch = If<Copyable::value, PolyVal, NoneSuch>;
491
492   using PolyRoot<I>::vptr_;
493
494   PolyRoot<I>& _polyRoot_() noexcept {
495     return *this;
496   }
497   PolyRoot<I> const& _polyRoot_() const noexcept {
498     return *this;
499   }
500
501   Data* _data_() noexcept {
502     return PolyAccess::data(*this);
503   }
504   Data const* _data_() const noexcept {
505     return PolyAccess::data(*this);
506   }
507
508  public:
509   /**
510    * Default constructor.
511    * \post `poly_empty(*this) == true`
512    */
513   PolyVal() = default;
514   /**
515    * Move constructor.
516    * \post `poly_empty(that) == true`
517    */
518   PolyVal(PolyVal&& that) noexcept;
519   /**
520    * A copy constructor if `I` is copyable; otherwise, a useless constructor
521    * from a private, incomplete type.
522    */
523   /* implicit */ PolyVal(PolyOrNonesuch const& that);
524
525   ~PolyVal();
526
527   /**
528    * Inherit any constructors defined by any of the interfaces.
529    */
530   using PolyImpl<I>::PolyImpl;
531
532   /**
533    * Copy assignment, destroys the object currently held (if any) and makes
534    * `*this` equal to `that` by stealing its guts.
535    */
536   Poly<I>& operator=(PolyVal that) noexcept;
537
538   /**
539    * Construct a Poly<I> from a concrete type that satisfies the I concept
540    */
541   template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
542   /* implicit */ PolyVal(T&& t);
543
544   /**
545    * Construct a `Poly` from a compatible `Poly`. "Compatible" here means: the
546    * other interface extends this one either directly or indirectly.
547    */
548   template <class I2, std::enable_if_t<ValueCompatible<I, I2>::value, int> = 0>
549   /* implicit */ PolyVal(Poly<I2> that);
550
551   /**
552    * Assign to this `Poly<I>` from a concrete type that satisfies the `I`
553    * concept.
554    */
555   template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
556   Poly<I>& operator=(T&& t);
557
558   /**
559    * Assign a compatible `Poly` to `*this`. "Compatible" here means: the
560    * other interface extends this one either directly or indirectly.
561    */
562   template <class I2, std::enable_if_t<ValueCompatible<I, I2>::value, int> = 0>
563   Poly<I>& operator=(Poly<I2> that);
564
565   /**
566    * Swaps the values of two `Poly` objects.
567    */
568   void swap(Poly<I>& that) noexcept;
569 };
570
571 ////////////////////////////////////////////////////////////////////////////////
572 /**
573  * The implementation of `Poly` for when the interface type is
574  * reference-quelified, like `Poly<SemuRegular &>`.
575  */
576 template <class I>
577 struct PolyRef : private PolyImpl<I> {
578  private:
579   friend PolyAccess;
580
581   AddCvrefOf<PolyRoot<I>, I>& _polyRoot_() const noexcept;
582
583   Data* _data_() noexcept {
584     return PolyAccess::data(*this);
585   }
586   Data const* _data_() const noexcept {
587     return PolyAccess::data(*this);
588   }
589
590   static constexpr RefType refType() noexcept;
591
592  protected:
593   template <class That, class I2>
594   PolyRef(That&& that, Type<I2>);
595
596  public:
597   /**
598    * Copy constructor
599    * \post `&poly_cast<T>(*this) == &poly_cast<T>(that)`, where `T` is the
600    *       type of the object held by `that`.
601    */
602   PolyRef(PolyRef const& that) noexcept;
603
604   /**
605    * Copy assignment
606    * \post `&poly_cast<T>(*this) == &poly_cast<T>(that)`, where `T` is the
607    *       type of the object held by `that`.
608    */
609   Poly<I>& operator=(PolyRef const& that) noexcept;
610
611   /**
612    * Construct a `Poly<I>` from a concrete type that satisfies concept `I`.
613    * \post `!poly_empty(*this)`
614    */
615   template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
616   /* implicit */ PolyRef(T&& t) noexcept;
617
618   /**
619    * Construct a `Poly<I>` from a compatible `Poly<I2>`.
620    */
621   template <
622       class I2,
623       std::enable_if_t<ReferenceCompatible<I, I2, I2&&>::value, int> = 0>
624   /* implicit */ PolyRef(Poly<I2>&& that) noexcept(
625       std::is_reference<I2>::value);
626
627   template <
628       class I2,
629       std::enable_if_t<ReferenceCompatible<I, I2, I2&>::value, int> = 0>
630   /* implicit */ PolyRef(Poly<I2>& that) noexcept(std::is_reference<I2>::value)
631       : PolyRef{that, Type<I2>{}} {}
632
633   template <
634       class I2,
635       std::enable_if_t<ReferenceCompatible<I, I2, I2 const&>::value, int> = 0>
636   /* implicit */ PolyRef(Poly<I2> const& that) noexcept(
637       std::is_reference<I2>::value)
638       : PolyRef{that, Type<I2>{}} {}
639
640   /**
641    * Assign to a `Poly<I>` from a concrete type that satisfies concept `I`.
642    * \post `!poly_empty(*this)`
643    */
644   template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
645   Poly<I>& operator=(T&& t) noexcept;
646
647   /**
648    * Assign to `*this` from another compatible `Poly`.
649    */
650   template <
651       class I2,
652       std::enable_if_t<ReferenceCompatible<I, I2, I2&&>::value, int> = 0>
653   Poly<I>& operator=(Poly<I2>&& that) noexcept(std::is_reference<I2>::value);
654
655   /**
656    * \overload
657    */
658   template <
659       class I2,
660       std::enable_if_t<ReferenceCompatible<I, I2, I2&>::value, int> = 0>
661   Poly<I>& operator=(Poly<I2>& that) noexcept(std::is_reference<I2>::value);
662
663   /**
664    * \overload
665    */
666   template <
667       class I2,
668       std::enable_if_t<ReferenceCompatible<I, I2, I2 const&>::value, int> = 0>
669   Poly<I>& operator=(Poly<I2> const& that) noexcept(
670       std::is_reference<I2>::value);
671
672   /**
673    * Swap which object this `Poly` references ("shallow" swap).
674    */
675   void swap(Poly<I>& that) noexcept;
676
677   /**
678    * Get a reference to the interface, with correct `const`-ness applied.
679    */
680   AddCvrefOf<PolyImpl<I>, I>& get() const noexcept;
681
682   /**
683    * Get a reference to the interface, with correct `const`-ness applied.
684    */
685   AddCvrefOf<PolyImpl<I>, I>& operator*() const noexcept {
686     return get();
687   }
688
689   /**
690    * Get a pointer to the interface, with correct `const`-ness applied.
691    */
692   auto operator-> () const noexcept {
693     return &get();
694   }
695 };
696
697 template <class I>
698 using PolyValOrRef = If<std::is_reference<I>::value, PolyRef<I>, PolyVal<I>>;
699 } // namespace detail
700 /// \endcond
701
702 /**
703  * `Poly` is a class template that makes it relatively easy to define a
704  * type-erasing polymorphic object wrapper.
705  *
706  * \par Type-erasure
707  *
708  * \par
709  * `std::function` is one example of a type-erasing polymorphic object wrapper;
710  * `folly::exception_wrapper` is another. Type-erasure is often used as an
711  * alternative to dynamic polymorphism via inheritance-based virtual dispatch.
712  * The distinguishing characteristic of type-erasing wrappers are:
713  * \li **Duck typing:** Types do not need to inherit from an abstract base
714  *     class in order to be assignable to a type-erasing wrapper; they merely
715  *     need to satisfy a particular interface.
716  * \li **Value semantics:** Type-erasing wrappers are objects that can be
717  *     passed around _by value_. This is in contrast to abstract base classes
718  *     which must be passed by reference or by pointer or else suffer from
719  *     _slicing_, which causes them to lose their polymorphic behaviors.
720  *     Reference semantics make it difficult to reason locally about code.
721  * \li **Automatic memory management:** When dealing with inheritance-based
722  *     dynamic polymorphism, it is often necessary to allocate and manage
723  *     objects on the heap. This leads to a proliferation of `shared_ptr`s and
724  *     `unique_ptr`s in APIs, complicating their point-of-use. APIs that take
725  *     type-erasing wrappers, on the other hand, can often store small objects
726  *     in-situ, with no dynamic allocation. The memory management, if any, is
727  *     handled for you, and leads to cleaner APIs: consumers of your API don't
728  *     need to pass `shared_ptr<AbstractBase>`; they can simply pass any object
729  *     that satisfies the interface you require. (`std::function` is a
730  *     particularly compelling example of this benefit. Far worse would be an
731  *     inheritance-based callable solution like
732  *     `shared_ptr<ICallable<void(int)>>`. )
733  *
734  * \par Example: Defining a type-erasing function wrapper with `folly::Poly`
735  *
736  * \par
737  * Defining a polymorphic wrapper with `Poly` is a matter of defining two
738  * things:
739  * \li An *interface*, consisting of public member functions, and
740  * \li A *mapping* from a concrete type to a set of member function bindings.
741  *
742  * Below is a (heavily commented) example of a simple implementation of a
743  * `std::function`-like polymorphic wrapper. Its interface has only a simgle
744  * member function: `operator()`
745  *
746  *     // An interface for a callable object of a particular signature, Fun
747  *     // (most interfaces don't need to be templates, FWIW).
748  *     template <class Fun>
749  *     struct IFunction;
750  *
751  *     template <class R, class... As>
752  *     struct IFunction<R(As...)> {
753  *       // An interface is defined as a nested class template called
754  *       // Interface that takes a single template parameter, Base, from
755  *       // which it inherits.
756  *       template <class Base>
757  *       struct Interface : Base {
758  *         // The Interface has public member functions. These become the
759  *         // public interface of the resulting Poly instantiation.
760  *         // (Implementation note: Poly<IFunction<Sig>> will publicly
761  *         // inherit from this struct, which is what gives it the right
762  *         // member functions.)
763  *         R operator()(As... as) const {
764  *           // The definition of each member function in your interface will
765  *           // always consist of a single line dispatching to
766  *           // folly::poly_call<N>. The "N" corresponds to the N-th member
767  *           // function in the list of member function bindings, Members,
768  *           // defined below. The first argument will always be *this, and the
769  *           // rest of the arguments should simply forward (if necessary) the
770  *           // member function's arguments.
771  *           return static_cast<R>(
772  *               folly::poly_call<0>(*this, std::forward<As>(as)...));
773  *         }
774  *       };
775  *
776  *       // The "Members" alias template is a comma-separated list of bound
777  *       // member functions for a given concrete type "T". The
778  *       // "FOLLY_POLY_MEMBERS" macro accepts a comma-separated list, and the
779  *       // (optional) "FOLLY_POLY_MEMBER" macro lets you disambiguate overloads
780  *       // by explicitly specifying the function signature the target member
781  *       // function should have. In this case, we require "T" to have a
782  *       // function call operator with the signature `R(As...) const`.
783  *       //
784  *       // If you are using a C++17-compatible compiler, you can do away with
785  *       // the macros and write this as:
786  *       //
787  *       //   template <class T>
788  *       //   using Members = folly::PolyMembers<
789  *       //       folly::sig<R(As...) const>(&T::operator())>;
790  *       //
791  *       // And since `folly::sig` is only needed for disambiguation in case of
792  *       // overloads, if you are not concerned about objects with overloaded
793  *       // function call operators, it could be further simplified to:
794  *       //
795  *       //   template <class T>
796  *       //   using Members = folly::PolyMembers<&T::operator()>;
797  *       //
798  *       template <class T>
799  *       using Members = FOLLY_POLY_MEMBERS(
800  *           FOLLY_POLY_MEMBER(R(As...) const, &T::operator()));
801  *     };
802  *
803  *     // Now that we have defined the interface, we can pass it to Poly to
804  *     // create our type-erasing wrapper:
805  *     template <class Fun>
806  *     using Function = Poly<IFunction<Fun>>;
807  *
808  * \par
809  * Given the above definition of `Function`, users can now initialize instances
810  * of (say) `Function<int(int, int)>` with function objects like
811  * `std::plus<int>` and `std::multiplies<int>`, as below:
812  *
813  *     Function<int(int, int)> fun = std::plus<int>{};
814  *     assert(5 == fun(2, 3));
815  *     fun = std::multiplies<int>{};
816  *     assert(6 = fun(2, 3));
817  *
818  * \par Defining an interface with C++17
819  *
820  * \par
821  * With C++17, defining an interface to be used with `Poly` is fairly
822  * straightforward. As in the `Function` example above, there is a struct with
823  * a nested `Interface` class template and a nested `Members` alias template.
824  * No macros are needed with C++17.
825  * \par
826  * Imagine we were defining something like a Java-style iterator. If we are
827  * using a C++17 compiler, our interface would look something like this:
828  *
829  *     template <class Value>
830  *     struct IJavaIterator {
831  *       template <class Base>
832  *       struct Interface : Base {
833  *         bool Done() const { return folly::poly_call<0>(*this); }
834  *         Value Current() const { return folly::poly_call<1>(*this); }
835  *         void Next() { folly::poly_call<2>(*this); }
836  *       };
837  *       // NOTE: This works in C++17 only:
838  *       template <class T>
839  *       using Members = folly::PolyMembers<&T::Done, &T::Current, &T::Next>;
840  *     };
841  *
842  *     template <class Value>
843  *     using JavaIterator = Poly<IJavaIterator>;
844  *
845  * \par
846  * Given the above definition, `JavaIterator<int>` can be used to hold instances
847  * of any type that has `Done`, `Current`, and `Next` member functions with the
848  * correct (or compatible) signatures.
849  *
850  * \par
851  * The presence of overloaded member functions complicates this picture. Often,
852  * property members are faked in C++ with `const` and non-`const` member
853  * function overloads, like in the interface specified below:
854  *
855  *     struct IIntProperty {
856  *       template <class Base>
857  *       struct Interface : Base {
858  *         int Value() const { return folly::poly_call<0>(*this); }
859  *         void Value(int i) { folly::poly_call<1>(*this, i); }
860  *       };
861  *       // NOTE: This works in C++17 only:
862  *       template <class T>
863  *       using Members = folly::PolyMembers<
864  *         folly::sig<int() const>(&T::Value),
865  *         folly::sig<void(int)>(&T::Value)>;
866  *     };
867  *
868  *     using IntProperty = Poly<IIntProperty>;
869  *
870  * \par
871  * Now, any object that has `Value` members of compatible signatures can be
872  * assigned to instances of `IntProperty` object. Note how `folly::sig` is used
873  * to disambiguate the overloads of `&T::Value`.
874  *
875  * \par Defining an interface with C++14
876  *
877  * \par
878  * In C++14, the nice syntax above doesn't work, so we have to resort to macros.
879  * The two examples above would look like this:
880  *
881  *     template <class Value>
882  *     struct IJavaIterator {
883  *       template <class Base>
884  *       struct Interface : Base {
885  *         bool Done() const { return folly::poly_call<0>(*this); }
886  *         Value Current() const { return folly::poly_call<1>(*this); }
887  *         void Next() { folly::poly_call<2>(*this); }
888  *       };
889  *       // NOTE: This works in C++14 and C++17:
890  *       template <class T>
891  *       using Members = FOLLY_POLY_MEMBERS(&T::Done, &T::Current, &T::Next);
892  *     };
893  *
894  *     template <class Value>
895  *     using JavaIterator = Poly<IJavaIterator>;
896  *
897  * \par
898  * and
899  *
900  *     struct IIntProperty {
901  *       template <class Base>
902  *       struct Interface : Base {
903  *         int Value() const { return folly::poly_call<0>(*this); }
904  *         void Value(int i) { return folly::poly_call<1>(*this, i); }
905  *       };
906  *       // NOTE: This works in C++14 and C++17:
907  *       template <class T>
908  *       using Members = FOLLY_POLY_MEMBERS(
909  *         FOLLY_POLY_MEMBER(int() const, &T::Value),
910  *         FOLLY_POLY_MEMBER(void(int), &T::Value));
911  *     };
912  *
913  *     using IntProperty = Poly<IIntProperty>;
914  *
915  * \par Extending interfaces
916  *
917  * \par
918  * One typical advantage of inheritance-based solutions to runtime polymorphism
919  * is that one polymorphic interface could extend another through inheritance.
920  * The same can be accomplished with type-erasing polymorphic wrappers. In
921  * the `Poly` library, you can use `folly::PolyExtends` to say that one
922  * interface extends another.
923  *
924  *     struct IFoo {
925  *       template <class Base>
926  *       struct Interface : Base {
927  *         void Foo() const { return folly::poly_call<0>(*this); }
928  *       };
929  *       template <class T>
930  *       using Members = FOLLY_POLY_MEMBERS(&T::Foo);
931  *     };
932  *
933  *     // The IFooBar interface extends the IFoo interface
934  *     struct IFooBar : PolyExtends<IFoo> {
935  *       template <class Base>
936  *       struct Interface : Base {
937  *         void Bar() const { return folly::poly_call<0>(*this); }
938  *       };
939  *       template <class T>
940  *       using Members = FOLLY_POLY_MEMBERS(&T::Bar);
941  *     };
942  *
943  *     using FooBar = Poly<IFooBar>;
944  *
945  * \par
946  * Given the above defintion, instances of type `FooBar` have both `Foo()` and
947  * `Bar()` member functions.
948  *
949  * \par
950  * The sensible conversions exist between a wrapped derived type and a wrapped
951  * base type. For instance, assuming `IDerived` extends `IBase` with
952  * `PolyExtends`:
953  *
954  *     Poly<IDerived> derived = ...;
955  *     Poly<IBase> base = derived; // This conversion is OK.
956  *
957  * \par
958  * As you would expect, there is no conversion in the other direction, and at
959  * present there is no `Poly` equivalent to `dynamic_cast`.
960  *
961  * \par Type-erasing polymorphic reference wrappers
962  *
963  * \par
964  * Sometimes you don't need to own a copy of an object; a reference will do. For
965  * that you can use `Poly` to capture a _reference_ to an object satisfying an
966  * interface rather than the whole object itself. The syntax is intuitive.
967  *
968  *     int i = 42;
969  *     // Capture a mutable reference to an object of any IRegular type:
970  *     Poly<IRegular &> intRef = i;
971  *     assert(42 == folly::poly_cast<int>(intRef));
972  *     // Assert that we captured the address of "i":
973  *     assert(&i == &folly::poly_cast<int>(intRef));
974  *
975  * \par
976  * A reference-like `Poly` has a different interface than a value-like `Poly`.
977  * Rather than calling member functions with the `obj.fun()` syntax, you would
978  * use the `obj->fun()` syntax. This is for the sake of `const`-correctness.
979  * For example, consider the code below:
980  *
981  *     struct IFoo {
982  *       template <class Base>
983  *       struct Interface {
984  *         void Foo() { folly::poly_call<0>(*this); }
985  *       };
986  *       template <class T>
987  *       using Members = folly::PolyMembers<&T::Foo>;
988  *     };
989  *
990  *     struct SomeFoo {
991  *       void Foo() { std::printf("SomeFoo::Foo\n"); }
992  *     };
993  *
994  *     SomeFoo foo;
995  *     Poly<IFoo &> const anyFoo = foo;
996  *     anyFoo->Foo(); // prints "SomeFoo::Foo"
997  *
998  * \par
999  * Notice in the above code that the `Foo` member function is non-`const`.
1000  * Notice also that the `anyFoo` object is `const`. However, since it has
1001  * captured a non-`const` reference to the `foo` object, it should still be
1002  * possible to dispatch to the non-`const` `Foo` member function. When
1003  * instantiated with a reference type, `Poly` has an overloaded `operator->`
1004  * member that returns a pointer to the `IFoo` interface with the correct
1005  * `const`-ness, which makes this work.
1006  *
1007  * \par
1008  * The same mechanism also prevents users from calling non-`const` member
1009  * functions on `Poly` objects that have captured `const` references, which
1010  * would violate `const`-correctness.
1011  *
1012  * \par
1013  * Sensible conversions exist between non-reference and reference `Poly`s. For
1014  * instance:
1015  *
1016  *     Poly<IRegular> value = 42;
1017  *     Poly<IRegular &> mutable_ref = value;
1018  *     Poly<IRegular const &> const_ref = mutable_ref;
1019  *
1020  *     assert(&poly_cast<int>(value) == &poly_cast<int>(mutable_ref));
1021  *     assert(&poly_cast<int>(value) == &poly_cast<int>(const_ref));
1022  *
1023  * \par Non-member functions (C++17)
1024  *
1025  * \par
1026  * If you wanted to write the interface `ILogicallyNegatable`, which captures
1027  * all types that can be negated with unary `operator!`, you could do it
1028  * as we've shown above, by binding `&T::operator!` in the nested `Members`
1029  * alias template, but that has the problem that it won't work for types that
1030  * have defined unary `operator!` as a free function. To handle this case,
1031  * the `Poly` library lets you use a free function instead of a member function
1032  * when creating a binding.
1033  *
1034  * \par
1035  * With C++17 you may use a lambda to create a binding, as shown in the example
1036  * below:
1037  *
1038  *     struct ILogicallyNegatable {
1039  *       template <class Base>
1040  *       struct Interface : Base {
1041  *         bool operator!() const { return folly::poly_call<0>(*this); }
1042  *       };
1043  *       template <class T>
1044  *       using Members = folly::PolyMembers<
1045  *         +[](T const& t) -> decltype(!t) { return !t; }>;
1046  *     };
1047  *
1048  * \par
1049  * This requires some explanation. The unary `operator+` in front of the lambda
1050  * is necessary! It causes the lambda to decay to a C-style function pointer,
1051  * which is one of the types that `folly::PolyMembers` accepts. The `decltype`
1052  * in the lambda return type is also necessary. Through the magic of SFINAE, it
1053  * will cause `Poly<ILogicallyNegatable>` to reject any types that don't support
1054  * unary `operator!`.
1055  *
1056  * \par
1057  * If you are using a free function to create a binding, the first parameter is
1058  * implicitly the `this` parameter. It will receive the type-erased object.
1059  *
1060  * \par Non-member functions (C++14)
1061  *
1062  * \par
1063  * If you are using a C++14 compiler, the defintion of `ILogicallyNegatable`
1064  * above will fail because lambdas are not `constexpr`. We can get the same
1065  * effect by writing the lambda as a named free function, as show below:
1066  *
1067  *     struct ILogicallyNegatable {
1068  *       template <class Base>
1069  *       struct Interface : Base {
1070  *         bool operator!() const { return folly::poly_call<0>(*this); }
1071  *       };
1072  *
1073  *       template <class T>
1074  *       static auto negate(T const& t) -> decltype(!t) { return !t; }
1075  *
1076  *       template <class T>
1077  *       using Members = FOLLY_POLY_MEMBERS(&negate<T>);
1078  *     };
1079  *
1080  * \par
1081  * As with the example that uses the lambda in the preceding section, the first
1082  * parameter is implicitly the `this` parameter. It will receive the type-erased
1083  * object.
1084  *
1085  * \par Multi-dispatch
1086  *
1087  * \par
1088  * What if you want to create an `IAddable` interface for things that can be
1089  * added? Adding requires _two_ objects, both of which are type-erased. This
1090  * interface requires dispatching on both objects, doing the addition only
1091  * if the types are the same. For this we make use of the `PolySelf` template
1092  * alias to define an interface that takes more than one object of the the
1093  * erased type.
1094  *
1095  *     struct IAddable {
1096  *       template <class Base>
1097  *       struct Interface : Base {
1098  *         friend PolySelf<Base, Decay>
1099  *         operator+(PolySelf<Base> const& a, PolySelf<Base> const& b) {
1100  *           return folly::poly_call<0, IAddable>(a, b);
1101  *         }
1102  *       };
1103  *
1104  *       template <class T>
1105  *       using Members = folly::PolyMembers<
1106  *         +[](T const& a, T const& b) -> decltype(a + b) { return a + b; }>;
1107  *     };
1108  *
1109  * \par
1110  * Given the above defintion of `IAddable` we would be able to do the following:
1111  *
1112  *     Poly<IAddable> a = 2, b = 3;
1113  *     Poly<IAddable> c = a + b;
1114  *     assert(poly_cast<int>(c) == 5);
1115  *
1116  * \par
1117  * If `a` and `b` stored objects of different types, a `BadPolyCast` exception
1118  * would be thrown.
1119  *
1120  * \par Move-only types
1121  *
1122  * \par
1123  * If you want to store move-only types, then your interface should extend the
1124  * `IMoveOnly` interface.
1125  *
1126  * \par Implementation notes
1127  * \par
1128  * `Poly` will store "small" objects in an internal buffer, avoiding the cost of
1129  * of dynamic allocations. At present, this size is not configurable; it is
1130  * pegged at the size of two `double`s.
1131  *
1132  * \par
1133  * `Poly` objects are always nothrow movable. If you store an object in one that
1134  * has a potentially throwing move contructor, the object will be stored on the
1135  * heap, even if it could fit in the internal storage of the `Poly` object.
1136  * (So be sure to give your objects nothrow move constructors!)
1137  *
1138  * \par
1139  * `Poly` implements type-erasure in a manner very similar to how the compiler
1140  * accomplishes virtual dispatch. Every `Poly` object contains a pointer to a
1141  * table of function pointers. Member function calls involve a double-
1142  * indirection: once through the v-pointer, and other indirect function call
1143  * through the function pointer.
1144  */
1145 template <class I>
1146 struct Poly final : detail::PolyValOrRef<I> {
1147   friend detail::PolyAccess;
1148   Poly() = default;
1149   using detail::PolyValOrRef<I>::PolyValOrRef;
1150   using detail::PolyValOrRef<I>::operator=;
1151 };
1152
1153 /**
1154  * Swap two `Poly<I>` instances.
1155  */
1156 template <class I>
1157 void swap(Poly<I>& left, Poly<I>& right) noexcept {
1158   left.swap(right);
1159 }
1160
1161 /**
1162  * Pseudo-function template handy for disambiguating function overloads.
1163  *
1164  * For example, given:
1165  *     struct S {
1166  *       int property() const;
1167  *       void property(int);
1168  *     };
1169  *
1170  * You can get a member function pointer to the first overload with:
1171  *     folly::sig<int()const>(&S::property);
1172  *
1173  * This is arguably a nicer syntax that using the built-in `static_cast`:
1174  *     static_cast<int (S::*)() const>(&S::property);
1175  *
1176  * `sig` is also more permissive than `static_cast` about `const`. For instance,
1177  * the following also works:
1178  *     folly::sig<int()>(&S::property);
1179  *
1180  * The above is permitted
1181  */
1182 template <class Sig>
1183 FOLLY_INLINE_CONSTEXPR detail::Sig<Sig> const sig = {};
1184
1185 } // namespace folly
1186
1187 #include <folly/Poly-inl.h>
1188
1189 #undef FOLLY_INLINE_CONSTEXPR