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