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