2 * Copyright 2017-present Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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?
30 #include <type_traits>
34 #include <folly/Assume.h>
35 #include <folly/CppAttributes.h>
36 #include <folly/Traits.h>
37 #include <folly/detail/TypeList.h>
39 #if !defined(__cpp_inline_variables)
40 #define FOLLY_INLINE_CONSTEXPR constexpr
42 #define FOLLY_INLINE_CONSTEXPR inline constexpr
45 #include <folly/detail/PolyDetail.h>
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`.
57 * It can be used within interface definitions to declare members that accept
58 * other `Poly` objects of the same type as `*this`.
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:
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>;
78 * struct Bar : PolyExtends<Foo> {
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 &>`
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 &>`
100 class Tfx = detail::MetaIdentity,
101 class Access = detail::PolyAccess>
102 using PolySelf = decltype(Access::template self_<Node, Tfx>());
105 * When used in conjunction with `PolySelf`, controls how to construct `Poly`
106 * types related to the one currently being instantiated.
110 using PolyDecay = detail::MetaQuote<std::decay_t>;
112 #if !defined(__cpp_template_auto)
115 * Use `FOLLY_POLY_MEMBERS(MEMS...)` on pre-C++17 compilers to specify a
116 * comma-separated list of member function bindings.
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); }
127 * using Members = FOLLY_POLY_MEMBERS(&T::foo, &T::bar);
130 #define FOLLY_POLY_MEMBERS(...) \
131 typename decltype(::folly::detail::deduceMembers( \
132 __VA_ARGS__))::template Members<__VA_ARGS__>
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
143 * template <class Base> struct Interface : Base {
144 * int foo() const { return folly::poly_call<0>(*this); }
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)
152 #define FOLLY_POLY_MEMBER(SIG, MEM) \
153 ::folly::detail::MemberDef< \
154 ::folly::detail::Member<decltype(::folly::sig<SIG>(MEM)), MEM>>::value
157 * A list of member function bindings.
159 template <class... Ts>
160 using PolyMembers = detail::TypeList<Ts...>;
163 #define FOLLY_POLY_MEMBER(SIG, MEM) ::folly::sig<SIG>(MEM)
164 #define FOLLY_POLY_MEMBERS(...) ::folly::PolyMembers<__VA_ARGS__>
166 template <auto... Ps>
167 struct PolyMembers {};
172 * Exception type that is thrown on invalid access of an empty `Poly` object.
174 struct BadPolyAccess : std::exception {
175 BadPolyAccess() = default;
176 char const* what() const noexcept override {
177 return "BadPolyAccess";
182 * Exception type that is thrown when attempting to extract from a `Poly` a
183 * value of the wrong type.
185 struct BadPolyCast : std::bad_cast {
186 BadPolyCast() = default;
187 char const* what() const noexcept override {
188 return "BadPolyCast";
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.
199 * template <class Base> struct Interface : Base {
200 * void foo() { folly::poly_call<0>(*this); }
202 * template <class T> using Members = FOLLY_POLY_MEMBERS(&T::foo);
204 * struct IBar : PolyExtends<IFoo> {
205 * template <class Base> struct Interface : Base {
206 * void bar(int i) { folly::poly_call<0>(*this, i); }
208 * template <class T> using Members = FOLLY_POLY_MEMBERS(&T::bar);
211 template <class... I>
212 struct PolyExtends : virtual I... {
213 using Subsumptions = detail::TypeList<I...>;
215 template <class Base>
216 struct Interface : Base {
217 Interface() = default;
222 using Members = PolyMembers<>;
225 ////////////////////////////////////////////////////////////////////////////////
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.
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);
241 * static auto plus_(T const& a, T const& b) -> decltype(a + b) {
245 * using Members = FOLLY_POLY_MEMBERS(&plus_<std::decay_t<T>>);
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)...);
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)...);
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)...);
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)...);
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)...);
299 template <std::size_t N, class I, typename... As>
300 [[noreturn]] detail::Bottom poly_call(detail::ArchetypeBase const&, As&&...) {
301 assume_unreachable();
305 ////////////////////////////////////////////////////////////////////////////////
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
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
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));
324 template <class T, class I>
325 detail::AddCvrefOf<T, I>& poly_cast(detail::PolyRoot<I>& that) {
326 return detail::PolyAccess::cast<T>(that);
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);
337 template <class T, class I>
338 [[noreturn]] detail::AddCvrefOf<T, I>&& poly_cast(detail::ArchetypeRoot<I>&&) {
339 assume_unreachable();
343 template <class T, class I>
344 [[noreturn]] detail::AddCvrefOf<T, I>& poly_cast(detail::ArchetypeRoot<I>&) {
345 assume_unreachable();
349 template <class T, class I>
350 [[noreturn]] detail::AddCvrefOf<T, I> const& poly_cast(
351 detail::ArchetypeRoot<I> const&) { assume_unreachable(); }
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());
364 ////////////////////////////////////////////////////////////////////////////////
366 * Returns a reference to the `std::type_info` object corresponding to the
367 * object currently stored in `that`. If `that` is empty, returns
371 std::type_info const& poly_type(detail::PolyRoot<I> const& that) noexcept {
372 return detail::PolyAccess::type(that);
377 [[noreturn]] inline std::type_info const& poly_type(
378 detail::ArchetypeBase const&) noexcept {
379 assume_unreachable();
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());
390 ////////////////////////////////////////////////////////////////////////////////
392 * Returns `true` if `that` is not currently storing an object; `false`,
396 bool poly_empty(detail::PolyRoot<I> const& that) noexcept {
397 return detail::State::eEmpty == detail::PolyAccess::vtable(that)->state_;
402 constexpr bool poly_empty(detail::PolyRoot<I&&> const&) noexcept {
408 constexpr bool poly_empty(detail::PolyRoot<I&> const&) noexcept {
414 constexpr bool poly_empty(Poly<I&&> const&) noexcept {
420 constexpr bool poly_empty(Poly<I&> const&) noexcept {
425 [[noreturn]] inline bool poly_empty(detail::ArchetypeBase const&) noexcept {
426 assume_unreachable();
430 ////////////////////////////////////////////////////////////////////////////////
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
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));
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);
453 Poly<I const&> poly_move(detail::PolyRoot<I const&> const& that) noexcept {
454 return detail::PolyAccess::move(that);
459 [[noreturn]] inline detail::ArchetypeBase poly_move(
460 detail::ArchetypeBase const&) noexcept {
461 assume_unreachable();
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());
475 * The implementation for `Poly` for when the interface type is not
476 * reference-like qualified, as in `Poly<SemiRegular>`.
479 struct PolyVal : PolyImpl<I> {
484 using Copyable = std::is_copy_constructible<PolyImpl<I>>;
485 using PolyOrNonesuch = If<Copyable::value, PolyVal, NoneSuch>;
487 using PolyRoot<I>::vptr_;
489 PolyRoot<I>& _polyRoot_() noexcept {
492 PolyRoot<I> const& _polyRoot_() const noexcept {
496 Data* _data_() noexcept {
497 return PolyAccess::data(*this);
499 Data const* _data_() const noexcept {
500 return PolyAccess::data(*this);
505 * Default constructor.
506 * \post `poly_empty(*this) == true`
511 * \post `poly_empty(that) == true`
513 PolyVal(PolyVal&& that) noexcept;
515 * A copy constructor if `I` is copyable; otherwise, a useless constructor
516 * from a private, incomplete type.
518 /* implicit */ PolyVal(PolyOrNonesuch const& that);
523 * Inherit any constructors defined by any of the interfaces.
525 using PolyImpl<I>::PolyImpl;
528 * Copy assignment, destroys the object currently held (if any) and makes
529 * `*this` equal to `that` by stealing its guts.
531 Poly<I>& operator=(PolyVal that) noexcept;
534 * Construct a Poly<I> from a concrete type that satisfies the I concept
536 template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
537 /* implicit */ PolyVal(T&& t);
540 * Construct a `Poly` from a compatible `Poly`. "Compatible" here means: the
541 * other interface extends this one either directly or indirectly.
543 template <class I2, std::enable_if_t<ValueCompatible<I, I2>::value, int> = 0>
544 /* implicit */ PolyVal(Poly<I2> that);
547 * Assign to this `Poly<I>` from a concrete type that satisfies the `I`
550 template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
551 Poly<I>& operator=(T&& t);
554 * Assign a compatible `Poly` to `*this`. "Compatible" here means: the
555 * other interface extends this one either directly or indirectly.
557 template <class I2, std::enable_if_t<ValueCompatible<I, I2>::value, int> = 0>
558 Poly<I>& operator=(Poly<I2> that);
561 * Swaps the values of two `Poly` objects.
563 void swap(Poly<I>& that) noexcept;
566 ////////////////////////////////////////////////////////////////////////////////
568 * The implementation of `Poly` for when the interface type is
569 * reference-quelified, like `Poly<SemuRegular &>`.
572 struct PolyRef : private PolyImpl<I> {
576 AddCvrefOf<PolyRoot<I>, I>& _polyRoot_() const noexcept;
578 Data* _data_() noexcept {
579 return PolyAccess::data(*this);
581 Data const* _data_() const noexcept {
582 return PolyAccess::data(*this);
585 static constexpr RefType refType() noexcept;
588 template <class That, class I2>
589 PolyRef(That&& that, Type<I2>);
594 * \post `&poly_cast<T>(*this) == &poly_cast<T>(that)`, where `T` is the
595 * type of the object held by `that`.
597 PolyRef(PolyRef const& that) noexcept;
601 * \post `&poly_cast<T>(*this) == &poly_cast<T>(that)`, where `T` is the
602 * type of the object held by `that`.
604 Poly<I>& operator=(PolyRef const& that) noexcept;
607 * Construct a `Poly<I>` from a concrete type that satisfies concept `I`.
608 * \post `!poly_empty(*this)`
610 template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
611 /* implicit */ PolyRef(T&& t) noexcept;
614 * Construct a `Poly<I>` from a compatible `Poly<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);
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>{}} {}
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>{}} {}
636 * Assign to a `Poly<I>` from a concrete type that satisfies concept `I`.
637 * \post `!poly_empty(*this)`
639 template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
640 Poly<I>& operator=(T&& t) noexcept;
643 * Assign to `*this` from another compatible `Poly`.
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);
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);
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);
668 * Swap which object this `Poly` references ("shallow" swap).
670 void swap(Poly<I>& that) noexcept;
673 * Get a reference to the interface, with correct `const`-ness applied.
675 AddCvrefOf<PolyImpl<I>, I>& get() const noexcept;
678 * Get a reference to the interface, with correct `const`-ness applied.
680 AddCvrefOf<PolyImpl<I>, I>& operator*() const noexcept {
685 * Get a pointer to the interface, with correct `const`-ness applied.
687 auto operator-> () const noexcept {
693 using PolyValOrRef = If<std::is_reference<I>::value, PolyRef<I>, PolyVal<I>>;
694 } // namespace detail
698 * `Poly` is a class template that makes it relatively easy to define a
699 * type-erasing polymorphic object wrapper.
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)>>`. )
729 * \par Example: Defining a type-erasing function wrapper with `folly::Poly`
732 * Defining a polymorphic wrapper with `Poly` is a matter of defining two
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.
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()`
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>
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)...));
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`.
779 * // If you are using a C++17-compatible compiler, you can do away with
780 * // the macros and write this as:
782 * // template <class T>
783 * // using Members = folly::PolyMembers<
784 * // folly::sig<R(As...) const>(&T::operator())>;
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:
790 * // template <class T>
791 * // using Members = folly::PolyMembers<&T::operator()>;
794 * using Members = FOLLY_POLY_MEMBERS(
795 * FOLLY_POLY_MEMBER(R(As...) const, &T::operator()));
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>>;
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:
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));
813 * \par Defining an interface with C++17
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.
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:
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); }
832 * // NOTE: This works in C++17 only:
834 * using Members = folly::PolyMembers<&T::Done, &T::Current, &T::Next>;
837 * template <class Value>
838 * using JavaIterator = Poly<IJavaIterator>;
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.
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:
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); }
856 * // NOTE: This works in C++17 only:
858 * using Members = folly::PolyMembers<
859 * folly::sig<int() const>(&T::Value),
860 * folly::sig<void(int)>(&T::Value)>;
863 * using IntProperty = Poly<IIntProperty>;
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`.
870 * \par Defining an interface with C++14
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:
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); }
884 * // NOTE: This works in C++14 and C++17:
886 * using Members = FOLLY_POLY_MEMBERS(&T::Done, &T::Current, &T::Next);
889 * template <class Value>
890 * using JavaIterator = Poly<IJavaIterator>;
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); }
901 * // NOTE: This works in C++14 and C++17:
903 * using Members = FOLLY_POLY_MEMBERS(
904 * FOLLY_POLY_MEMBER(int() const, &T::Value),
905 * FOLLY_POLY_MEMBER(void(int), &T::Value));
908 * using IntProperty = Poly<IIntProperty>;
910 * \par Extending interfaces
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.
920 * template <class Base>
921 * struct Interface : Base {
922 * void Foo() const { return folly::poly_call<0>(*this); }
925 * using Members = FOLLY_POLY_MEMBERS(&T::Foo);
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); }
935 * using Members = FOLLY_POLY_MEMBERS(&T::Bar);
938 * using FooBar = Poly<IFooBar>;
941 * Given the above defintion, instances of type `FooBar` have both `Foo()` and
942 * `Bar()` member functions.
945 * The sensible conversions exist between a wrapped derived type and a wrapped
946 * base type. For instance, assuming `IDerived` extends `IBase` with
949 * Poly<IDerived> derived = ...;
950 * Poly<IBase> base = derived; // This conversion is OK.
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`.
956 * \par Type-erasing polymorphic reference wrappers
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.
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));
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:
977 * template <class Base>
979 * void Foo() { folly::poly_call<0>(*this); }
982 * using Members = folly::PolyMembers<&T::Foo>;
986 * void Foo() { std::printf("SomeFoo::Foo\n"); }
990 * Poly<IFoo &> const anyFoo = foo;
991 * anyFoo->Foo(); // prints "SomeFoo::Foo"
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.
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.
1008 * Sensible conversions exist between non-reference and reference `Poly`s. For
1011 * Poly<IRegular> value = 42;
1012 * Poly<IRegular &> mutable_ref = value;
1013 * Poly<IRegular const &> const_ref = mutable_ref;
1015 * assert(&poly_cast<int>(value) == &poly_cast<int>(mutable_ref));
1016 * assert(&poly_cast<int>(value) == &poly_cast<int>(const_ref));
1018 * \par Non-member functions (C++17)
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.
1030 * With C++17 you may use a lambda to create a binding, as shown in the example
1033 * struct ILogicallyNegatable {
1034 * template <class Base>
1035 * struct Interface : Base {
1036 * bool operator!() const { return folly::poly_call<0>(*this); }
1038 * template <class T>
1039 * using Members = folly::PolyMembers<
1040 * +[](T const& t) -> decltype(!t) { return !t; }>;
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!`.
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.
1055 * \par Non-member functions (C++14)
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:
1062 * struct ILogicallyNegatable {
1063 * template <class Base>
1064 * struct Interface : Base {
1065 * bool operator!() const { return folly::poly_call<0>(*this); }
1068 * template <class T>
1069 * static auto negate(T const& t) -> decltype(!t) { return !t; }
1071 * template <class T>
1072 * using Members = FOLLY_POLY_MEMBERS(&negate<T>);
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
1080 * \par Multi-dispatch
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
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);
1099 * template <class T>
1100 * using Members = folly::PolyMembers<
1101 * +[](T const& a, T const& b) -> decltype(a + b) { return a + b; }>;
1105 * Given the above defintion of `IAddable` we would be able to do the following:
1107 * Poly<IAddable> a = 2, b = 3;
1108 * Poly<IAddable> c = a + b;
1109 * assert(poly_cast<int>(c) == 5);
1112 * If `a` and `b` stored objects of different types, a `BadPolyCast` exception
1115 * \par Move-only types
1118 * If you want to store move-only types, then your interface should extend the
1119 * `IMoveOnly` interface.
1121 * \par Implementation notes
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.
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!)
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.
1141 struct Poly final : detail::PolyValOrRef<I> {
1142 friend detail::PolyAccess;
1144 using detail::PolyValOrRef<I>::PolyValOrRef;
1145 using detail::PolyValOrRef<I>::operator=;
1149 * Swap two `Poly<I>` instances.
1152 void swap(Poly<I>& left, Poly<I>& right) noexcept {
1157 * Pseudo-function template handy for disambiguating function overloads.
1159 * For example, given:
1161 * int property() const;
1162 * void property(int);
1165 * You can get a member function pointer to the first overload with:
1166 * folly::sig<int()const>(&S::property);
1168 * This is arguably a nicer syntax that using the built-in `static_cast`:
1169 * static_cast<int (S::*)() const>(&S::property);
1171 * `sig` is also more permissive than `static_cast` about `const`. For instance,
1172 * the following also works:
1173 * folly::sig<int()>(&S::property);
1175 * The above is permitted
1177 template <class Sig>
1178 FOLLY_INLINE_CONSTEXPR detail::Sig<Sig> const sig = {};
1180 } // namespace folly
1182 #include <folly/Poly-inl.h>
1184 #undef FOLLY_INLINE_CONSTEXPR