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?
28 #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 5
29 #error Folly.Poly requires gcc-5 or greater
34 #include <type_traits>
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>
44 #if !defined(__cpp_inline_variables)
45 #define FOLLY_INLINE_CONSTEXPR constexpr
47 #define FOLLY_INLINE_CONSTEXPR inline constexpr
50 #include <folly/detail/PolyDetail.h>
57 * Within the definition of interface `I`, `PolySelf<Base>` is an alias for
58 * the instance of `Poly` that is currently being instantiated. It is
59 * one of: `Poly<J>`, `Poly<J&&>`, `Poly<J&>`, or `Poly<J const&>`; where
60 * `J` is either `I` or some interface that extends `I`.
62 * It can be used within interface definitions to declare members that accept
63 * other `Poly` objects of the same type as `*this`.
65 * The first parameter may optionally be cv- and/or reference-qualified, in
66 * which case, the qualification is applies to the type of the interface in the
67 * resulting `Poly<>` instance. The second template parameter controls whether
68 * or not the interface is decayed before the cv-ref qualifiers of the first
69 * argument are applied. For example, given the following:
72 * template <class Base>
73 * struct Interface : Base {
74 * using A = PolySelf<Base>;
75 * using B = PolySelf<Base &>;
76 * using C = PolySelf<Base const &>;
77 * using X = PolySelf<Base, PolyDecay>;
78 * using Y = PolySelf<Base &, PolyDecay>;
79 * using Z = PolySelf<Base const &, PolyDecay>;
83 * struct Bar : PolyExtends<Foo> {
87 * Then for `Poly<Bar>`, the typedefs are aliases for the following types:
88 * - `A` is `Poly<Bar>`
89 * - `B` is `Poly<Bar &>`
90 * - `C` is `Poly<Bar const &>`
91 * - `X` is `Poly<Bar>`
92 * - `Y` is `Poly<Bar &>`
93 * - `Z` is `Poly<Bar const &>`
95 * And for `Poly<Bar &>`, the typedefs are aliases for the following types:
96 * - `A` is `Poly<Bar &>`
97 * - `B` is `Poly<Bar &>`
98 * - `C` is `Poly<Bar &>`
99 * - `X` is `Poly<Bar>`
100 * - `Y` is `Poly<Bar &>`
101 * - `Z` is `Poly<Bar const &>`
105 class Tfx = detail::MetaIdentity,
106 class Access = detail::PolyAccess>
107 using PolySelf = decltype(Access::template self_<Node, Tfx>());
110 * When used in conjunction with `PolySelf`, controls how to construct `Poly`
111 * types related to the one currently being instantiated.
115 using PolyDecay = detail::MetaQuote<std::decay_t>;
117 #if !defined(__cpp_template_auto)
120 * Use `FOLLY_POLY_MEMBERS(MEMS...)` on pre-C++17 compilers to specify a
121 * comma-separated list of member function bindings.
126 * template <class Base>
127 * struct Interface : Base {
128 * int foo() const { return folly::poly_call<0>(*this); }
129 * void bar() { folly::poly_call<1>(*this); }
132 * using Members = FOLLY_POLY_MEMBERS(&T::foo, &T::bar);
135 #define FOLLY_POLY_MEMBERS(...) \
136 typename decltype(::folly::detail::deduceMembers( \
137 __VA_ARGS__))::template Members<__VA_ARGS__>
140 * Use `FOLLY_POLY_MEMBER(SIG, MEM)` on pre-C++17 compilers to specify a member
141 * function binding that needs to be disambiguated because of overloads. `SIG`
142 * should the (possibly const-qualified) signature of the `MEM` member function
148 * template <class Base> struct Interface : Base {
149 * int foo() const { return folly::poly_call<0>(*this); }
151 * template <class T> using Members = FOLLY_POLY_MEMBERS(
152 * // This works even if T::foo is overloaded:
153 * FOLLY_POLY_MEMBER(int()const, &T::foo)
157 #define FOLLY_POLY_MEMBER(SIG, MEM) \
158 ::folly::detail::MemberDef< \
159 ::folly::detail::Member<decltype(::folly::sig<SIG>(MEM)), MEM>>::value
162 * A list of member function bindings.
164 template <class... Ts>
165 using PolyMembers = detail::TypeList<Ts...>;
168 #define FOLLY_POLY_MEMBER(SIG, MEM) ::folly::sig<SIG>(MEM)
169 #define FOLLY_POLY_MEMBERS(...) ::folly::PolyMembers<__VA_ARGS__>
171 template <auto... Ps>
172 struct PolyMembers {};
177 * Exception type that is thrown on invalid access of an empty `Poly` object.
179 struct FOLLY_EXPORT BadPolyAccess : std::exception {
180 BadPolyAccess() = default;
181 char const* what() const noexcept override {
182 return "BadPolyAccess";
187 * Exception type that is thrown when attempting to extract from a `Poly` a
188 * value of the wrong type.
190 struct FOLLY_EXPORT BadPolyCast : std::bad_cast {
191 BadPolyCast() = default;
192 char const* what() const noexcept override {
193 return "BadPolyCast";
198 * Used in the definition of a `Poly` interface to say that the current
199 * interface is an extension of a set of zero or more interfaces.
204 * template <class Base> struct Interface : Base {
205 * void foo() { folly::poly_call<0>(*this); }
207 * template <class T> using Members = FOLLY_POLY_MEMBERS(&T::foo);
209 * struct IBar : PolyExtends<IFoo> {
210 * template <class Base> struct Interface : Base {
211 * void bar(int i) { folly::poly_call<0>(*this, i); }
213 * template <class T> using Members = FOLLY_POLY_MEMBERS(&T::bar);
216 template <class... I>
217 struct PolyExtends : virtual I... {
218 using Subsumptions = detail::TypeList<I...>;
220 template <class Base>
221 struct Interface : Base {
222 Interface() = default;
227 using Members = PolyMembers<>;
230 ////////////////////////////////////////////////////////////////////////////////
232 * Call the N-th member of the currently-being-defined interface. When the
233 * first parameter is an object of type `PolySelf<Base>` (as opposed to `*this`)
234 * you must explicitly specify which interface through which to dispatch.
238 * template <class Base>
239 * struct Interface : Base {
240 * friend PolySelf<Base, Decay>
241 * operator+(PolySelf<Base> const& a, PolySelf<Base> const& b) {
242 * return folly::poly_call<0, IAddable>(a, b);
246 * static auto plus_(T const& a, T const& b) -> decltype(a + b) {
250 * using Members = FOLLY_POLY_MEMBERS(&plus_<std::decay_t<T>>);
255 template <std::size_t N, typename This, typename... As>
256 auto poly_call(This&& _this, As&&... as)
257 -> decltype(detail::PolyAccess::call<N>(
258 static_cast<This&&>(_this),
259 static_cast<As&&>(as)...)) {
260 return detail::PolyAccess::call<N>(
261 static_cast<This&&>(_this), static_cast<As&&>(as)...);
265 template <std::size_t N, class I, class Tail, typename... As>
266 decltype(auto) poly_call(detail::PolyNode<I, Tail>&& _this, As&&... as) {
267 using This = detail::InterfaceOf<I, detail::PolyNode<I, Tail>>;
268 return detail::PolyAccess::call<N>(
269 static_cast<This&&>(_this), static_cast<As&&>(as)...);
273 template <std::size_t N, class I, class Tail, typename... As>
274 decltype(auto) poly_call(detail::PolyNode<I, Tail>& _this, As&&... as) {
275 using This = detail::InterfaceOf<I, detail::PolyNode<I, Tail>>;
276 return detail::PolyAccess::call<N>(
277 static_cast<This&>(_this), static_cast<As&&>(as)...);
281 template <std::size_t N, class I, class Tail, typename... As>
282 decltype(auto) poly_call(detail::PolyNode<I, Tail> const& _this, As&&... as) {
283 using This = detail::InterfaceOf<I, detail::PolyNode<I, Tail>>;
284 return detail::PolyAccess::call<N>(
285 static_cast<This const&>(_this), static_cast<As&&>(as)...);
294 std::enable_if_t<detail::IsPoly<Poly>::value, int> = 0>
295 auto poly_call(Poly&& _this, As&&... as) -> decltype(poly_call<N, I>(
296 static_cast<Poly&&>(_this).get(),
297 static_cast<As&&>(as)...)) {
298 return poly_call<N, I>(
299 static_cast<Poly&&>(_this).get(), static_cast<As&&>(as)...);
304 template <std::size_t N, class I, typename... As>
305 [[noreturn]] detail::Bottom poly_call(detail::ArchetypeBase const&, As&&...) {
306 assume_unreachable();
310 ////////////////////////////////////////////////////////////////////////////////
312 * Try to cast the `Poly` object to the requested type. If the `Poly` stores an
313 * object of that type, return a reference to the object; otherwise, throw an
315 * \tparam T The (unqualified) type to which to cast the `Poly` object.
316 * \tparam Poly The type of the `Poly` object.
317 * \param that The `Poly` object to be cast.
318 * \return A reference to the `T` object stored in or refered to by `that`.
319 * \throw BadPolyAccess if `that` is empty.
320 * \throw BadPolyCast if `that` does not store or refer to an object of type
323 template <class T, class I>
324 detail::AddCvrefOf<T, I>&& poly_cast(detail::PolyRoot<I>&& that) {
325 return detail::PolyAccess::cast<T>(std::move(that));
329 template <class T, class I>
330 detail::AddCvrefOf<T, I>& poly_cast(detail::PolyRoot<I>& that) {
331 return detail::PolyAccess::cast<T>(that);
335 template <class T, class I>
336 detail::AddCvrefOf<T, I> const& poly_cast(detail::PolyRoot<I> const& that) {
337 return detail::PolyAccess::cast<T>(that);
342 template <class T, class I>
343 [[noreturn]] detail::AddCvrefOf<T, I>&& poly_cast(detail::ArchetypeRoot<I>&&) {
344 assume_unreachable();
348 template <class T, class I>
349 [[noreturn]] detail::AddCvrefOf<T, I>& poly_cast(detail::ArchetypeRoot<I>&) {
350 assume_unreachable();
354 template <class T, class I>
355 [[noreturn]] detail::AddCvrefOf<T, I> const& poly_cast(
356 detail::ArchetypeRoot<I> const&) { assume_unreachable(); }
363 std::enable_if_t<detail::IsPoly<Poly>::value, int> = 0>
364 constexpr auto poly_cast(Poly&& that)
365 -> decltype(poly_cast<T>(std::declval<Poly>().get())) {
366 return poly_cast<T>(static_cast<Poly&&>(that).get());
369 ////////////////////////////////////////////////////////////////////////////////
371 * Returns a reference to the `std::type_info` object corresponding to the
372 * object currently stored in `that`. If `that` is empty, returns
376 std::type_info const& poly_type(detail::PolyRoot<I> const& that) noexcept {
377 return detail::PolyAccess::type(that);
382 [[noreturn]] inline std::type_info const& poly_type(
383 detail::ArchetypeBase const&) noexcept {
384 assume_unreachable();
389 template <class Poly, std::enable_if_t<detail::IsPoly<Poly>::value, int> = 0>
390 constexpr auto poly_type(Poly const& that) noexcept
391 -> decltype(poly_type(that.get())) {
392 return poly_type(that.get());
395 ////////////////////////////////////////////////////////////////////////////////
397 * Returns `true` if `that` is not currently storing an object; `false`,
401 bool poly_empty(detail::PolyRoot<I> const& that) noexcept {
402 return detail::State::eEmpty == detail::PolyAccess::vtable(that)->state_;
407 constexpr bool poly_empty(detail::PolyRoot<I&&> const&) noexcept {
413 constexpr bool poly_empty(detail::PolyRoot<I&> const&) noexcept {
419 constexpr bool poly_empty(Poly<I&&> const&) noexcept {
425 constexpr bool poly_empty(Poly<I&> const&) noexcept {
430 [[noreturn]] inline bool poly_empty(detail::ArchetypeBase const&) noexcept {
431 assume_unreachable();
435 ////////////////////////////////////////////////////////////////////////////////
437 * Given a `Poly<I&>`, return a `Poly<I&&>`. Otherwise, when `I` is not a
438 * reference type, returns a `Poly<I>&&` when given a `Poly<I>&`, like
443 std::enable_if_t<detail::Not<std::is_reference<I>>::value, int> = 0>
444 constexpr Poly<I>&& poly_move(detail::PolyRoot<I>& that) noexcept {
445 return static_cast<Poly<I>&&>(static_cast<Poly<I>&>(that));
451 std::enable_if_t<detail::Not<std::is_const<I>>::value, int> = 0>
452 Poly<I&&> poly_move(detail::PolyRoot<I&> const& that) noexcept {
453 return detail::PolyAccess::move(that);
458 Poly<I const&> poly_move(detail::PolyRoot<I const&> const& that) noexcept {
459 return detail::PolyAccess::move(that);
464 [[noreturn]] inline detail::ArchetypeBase poly_move(
465 detail::ArchetypeBase const&) noexcept {
466 assume_unreachable();
471 template <class Poly, std::enable_if_t<detail::IsPoly<Poly>::value, int> = 0>
472 constexpr auto poly_move(Poly& that) noexcept
473 -> decltype(poly_move(that.get())) {
474 return poly_move(that.get());
480 * The implementation for `Poly` for when the interface type is not
481 * reference-like qualified, as in `Poly<SemiRegular>`.
484 struct PolyVal : PolyImpl<I> {
489 using Copyable = std::is_copy_constructible<PolyImpl<I>>;
490 using PolyOrNonesuch = If<Copyable::value, PolyVal, NoneSuch>;
492 using PolyRoot<I>::vptr_;
494 PolyRoot<I>& _polyRoot_() noexcept {
497 PolyRoot<I> const& _polyRoot_() const noexcept {
501 Data* _data_() noexcept {
502 return PolyAccess::data(*this);
504 Data const* _data_() const noexcept {
505 return PolyAccess::data(*this);
510 * Default constructor.
511 * \post `poly_empty(*this) == true`
516 * \post `poly_empty(that) == true`
518 PolyVal(PolyVal&& that) noexcept;
520 * A copy constructor if `I` is copyable; otherwise, a useless constructor
521 * from a private, incomplete type.
523 /* implicit */ PolyVal(PolyOrNonesuch const& that);
528 * Inherit any constructors defined by any of the interfaces.
530 using PolyImpl<I>::PolyImpl;
533 * Copy assignment, destroys the object currently held (if any) and makes
534 * `*this` equal to `that` by stealing its guts.
536 Poly<I>& operator=(PolyVal that) noexcept;
539 * Construct a Poly<I> from a concrete type that satisfies the I concept
541 template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
542 /* implicit */ PolyVal(T&& t);
545 * Construct a `Poly` from a compatible `Poly`. "Compatible" here means: the
546 * other interface extends this one either directly or indirectly.
548 template <class I2, std::enable_if_t<ValueCompatible<I, I2>::value, int> = 0>
549 /* implicit */ PolyVal(Poly<I2> that);
552 * Assign to this `Poly<I>` from a concrete type that satisfies the `I`
555 template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
556 Poly<I>& operator=(T&& t);
559 * Assign a compatible `Poly` to `*this`. "Compatible" here means: the
560 * other interface extends this one either directly or indirectly.
562 template <class I2, std::enable_if_t<ValueCompatible<I, I2>::value, int> = 0>
563 Poly<I>& operator=(Poly<I2> that);
566 * Swaps the values of two `Poly` objects.
568 void swap(Poly<I>& that) noexcept;
571 ////////////////////////////////////////////////////////////////////////////////
573 * The implementation of `Poly` for when the interface type is
574 * reference-quelified, like `Poly<SemuRegular &>`.
577 struct PolyRef : private PolyImpl<I> {
581 AddCvrefOf<PolyRoot<I>, I>& _polyRoot_() const noexcept;
583 Data* _data_() noexcept {
584 return PolyAccess::data(*this);
586 Data const* _data_() const noexcept {
587 return PolyAccess::data(*this);
590 static constexpr RefType refType() noexcept;
593 template <class That, class I2>
594 PolyRef(That&& that, Type<I2>);
599 * \post `&poly_cast<T>(*this) == &poly_cast<T>(that)`, where `T` is the
600 * type of the object held by `that`.
602 PolyRef(PolyRef const& that) noexcept;
606 * \post `&poly_cast<T>(*this) == &poly_cast<T>(that)`, where `T` is the
607 * type of the object held by `that`.
609 Poly<I>& operator=(PolyRef const& that) noexcept;
612 * Construct a `Poly<I>` from a concrete type that satisfies concept `I`.
613 * \post `!poly_empty(*this)`
615 template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
616 /* implicit */ PolyRef(T&& t) noexcept;
619 * Construct a `Poly<I>` from a compatible `Poly<I2>`.
623 std::enable_if_t<ReferenceCompatible<I, I2, I2&&>::value, int> = 0>
624 /* implicit */ PolyRef(Poly<I2>&& that) noexcept(
625 std::is_reference<I2>::value);
629 std::enable_if_t<ReferenceCompatible<I, I2, I2&>::value, int> = 0>
630 /* implicit */ PolyRef(Poly<I2>& that) noexcept(std::is_reference<I2>::value)
631 : PolyRef{that, Type<I2>{}} {}
635 std::enable_if_t<ReferenceCompatible<I, I2, I2 const&>::value, int> = 0>
636 /* implicit */ PolyRef(Poly<I2> const& that) noexcept(
637 std::is_reference<I2>::value)
638 : PolyRef{that, Type<I2>{}} {}
641 * Assign to a `Poly<I>` from a concrete type that satisfies concept `I`.
642 * \post `!poly_empty(*this)`
644 template <class T, std::enable_if_t<ModelsInterface<T, I>::value, int> = 0>
645 Poly<I>& operator=(T&& t) noexcept;
648 * Assign to `*this` from another compatible `Poly`.
652 std::enable_if_t<ReferenceCompatible<I, I2, I2&&>::value, int> = 0>
653 Poly<I>& operator=(Poly<I2>&& that) noexcept(std::is_reference<I2>::value);
660 std::enable_if_t<ReferenceCompatible<I, I2, I2&>::value, int> = 0>
661 Poly<I>& operator=(Poly<I2>& that) noexcept(std::is_reference<I2>::value);
668 std::enable_if_t<ReferenceCompatible<I, I2, I2 const&>::value, int> = 0>
669 Poly<I>& operator=(Poly<I2> const& that) noexcept(
670 std::is_reference<I2>::value);
673 * Swap which object this `Poly` references ("shallow" swap).
675 void swap(Poly<I>& that) noexcept;
678 * Get a reference to the interface, with correct `const`-ness applied.
680 AddCvrefOf<PolyImpl<I>, I>& get() const noexcept;
683 * Get a reference to the interface, with correct `const`-ness applied.
685 AddCvrefOf<PolyImpl<I>, I>& operator*() const noexcept {
690 * Get a pointer to the interface, with correct `const`-ness applied.
692 auto operator-> () const noexcept {
698 using PolyValOrRef = If<std::is_reference<I>::value, PolyRef<I>, PolyVal<I>>;
699 } // namespace detail
703 * `Poly` is a class template that makes it relatively easy to define a
704 * type-erasing polymorphic object wrapper.
709 * `std::function` is one example of a type-erasing polymorphic object wrapper;
710 * `folly::exception_wrapper` is another. Type-erasure is often used as an
711 * alternative to dynamic polymorphism via inheritance-based virtual dispatch.
712 * The distinguishing characteristic of type-erasing wrappers are:
713 * \li **Duck typing:** Types do not need to inherit from an abstract base
714 * class in order to be assignable to a type-erasing wrapper; they merely
715 * need to satisfy a particular interface.
716 * \li **Value semantics:** Type-erasing wrappers are objects that can be
717 * passed around _by value_. This is in contrast to abstract base classes
718 * which must be passed by reference or by pointer or else suffer from
719 * _slicing_, which causes them to lose their polymorphic behaviors.
720 * Reference semantics make it difficult to reason locally about code.
721 * \li **Automatic memory management:** When dealing with inheritance-based
722 * dynamic polymorphism, it is often necessary to allocate and manage
723 * objects on the heap. This leads to a proliferation of `shared_ptr`s and
724 * `unique_ptr`s in APIs, complicating their point-of-use. APIs that take
725 * type-erasing wrappers, on the other hand, can often store small objects
726 * in-situ, with no dynamic allocation. The memory management, if any, is
727 * handled for you, and leads to cleaner APIs: consumers of your API don't
728 * need to pass `shared_ptr<AbstractBase>`; they can simply pass any object
729 * that satisfies the interface you require. (`std::function` is a
730 * particularly compelling example of this benefit. Far worse would be an
731 * inheritance-based callable solution like
732 * `shared_ptr<ICallable<void(int)>>`. )
734 * \par Example: Defining a type-erasing function wrapper with `folly::Poly`
737 * Defining a polymorphic wrapper with `Poly` is a matter of defining two
739 * \li An *interface*, consisting of public member functions, and
740 * \li A *mapping* from a concrete type to a set of member function bindings.
742 * Below is a (heavily commented) example of a simple implementation of a
743 * `std::function`-like polymorphic wrapper. Its interface has only a simgle
744 * member function: `operator()`
746 * // An interface for a callable object of a particular signature, Fun
747 * // (most interfaces don't need to be templates, FWIW).
748 * template <class Fun>
751 * template <class R, class... As>
752 * struct IFunction<R(As...)> {
753 * // An interface is defined as a nested class template called
754 * // Interface that takes a single template parameter, Base, from
755 * // which it inherits.
756 * template <class Base>
757 * struct Interface : Base {
758 * // The Interface has public member functions. These become the
759 * // public interface of the resulting Poly instantiation.
760 * // (Implementation note: Poly<IFunction<Sig>> will publicly
761 * // inherit from this struct, which is what gives it the right
762 * // member functions.)
763 * R operator()(As... as) const {
764 * // The definition of each member function in your interface will
765 * // always consist of a single line dispatching to
766 * // folly::poly_call<N>. The "N" corresponds to the N-th member
767 * // function in the list of member function bindings, Members,
768 * // defined below. The first argument will always be *this, and the
769 * // rest of the arguments should simply forward (if necessary) the
770 * // member function's arguments.
771 * return static_cast<R>(
772 * folly::poly_call<0>(*this, std::forward<As>(as)...));
776 * // The "Members" alias template is a comma-separated list of bound
777 * // member functions for a given concrete type "T". The
778 * // "FOLLY_POLY_MEMBERS" macro accepts a comma-separated list, and the
779 * // (optional) "FOLLY_POLY_MEMBER" macro lets you disambiguate overloads
780 * // by explicitly specifying the function signature the target member
781 * // function should have. In this case, we require "T" to have a
782 * // function call operator with the signature `R(As...) const`.
784 * // If you are using a C++17-compatible compiler, you can do away with
785 * // the macros and write this as:
787 * // template <class T>
788 * // using Members = folly::PolyMembers<
789 * // folly::sig<R(As...) const>(&T::operator())>;
791 * // And since `folly::sig` is only needed for disambiguation in case of
792 * // overloads, if you are not concerned about objects with overloaded
793 * // function call operators, it could be further simplified to:
795 * // template <class T>
796 * // using Members = folly::PolyMembers<&T::operator()>;
799 * using Members = FOLLY_POLY_MEMBERS(
800 * FOLLY_POLY_MEMBER(R(As...) const, &T::operator()));
803 * // Now that we have defined the interface, we can pass it to Poly to
804 * // create our type-erasing wrapper:
805 * template <class Fun>
806 * using Function = Poly<IFunction<Fun>>;
809 * Given the above definition of `Function`, users can now initialize instances
810 * of (say) `Function<int(int, int)>` with function objects like
811 * `std::plus<int>` and `std::multiplies<int>`, as below:
813 * Function<int(int, int)> fun = std::plus<int>{};
814 * assert(5 == fun(2, 3));
815 * fun = std::multiplies<int>{};
816 * assert(6 = fun(2, 3));
818 * \par Defining an interface with C++17
821 * With C++17, defining an interface to be used with `Poly` is fairly
822 * straightforward. As in the `Function` example above, there is a struct with
823 * a nested `Interface` class template and a nested `Members` alias template.
824 * No macros are needed with C++17.
826 * Imagine we were defining something like a Java-style iterator. If we are
827 * using a C++17 compiler, our interface would look something like this:
829 * template <class Value>
830 * struct IJavaIterator {
831 * template <class Base>
832 * struct Interface : Base {
833 * bool Done() const { return folly::poly_call<0>(*this); }
834 * Value Current() const { return folly::poly_call<1>(*this); }
835 * void Next() { folly::poly_call<2>(*this); }
837 * // NOTE: This works in C++17 only:
839 * using Members = folly::PolyMembers<&T::Done, &T::Current, &T::Next>;
842 * template <class Value>
843 * using JavaIterator = Poly<IJavaIterator>;
846 * Given the above definition, `JavaIterator<int>` can be used to hold instances
847 * of any type that has `Done`, `Current`, and `Next` member functions with the
848 * correct (or compatible) signatures.
851 * The presence of overloaded member functions complicates this picture. Often,
852 * property members are faked in C++ with `const` and non-`const` member
853 * function overloads, like in the interface specified below:
855 * struct IIntProperty {
856 * template <class Base>
857 * struct Interface : Base {
858 * int Value() const { return folly::poly_call<0>(*this); }
859 * void Value(int i) { folly::poly_call<1>(*this, i); }
861 * // NOTE: This works in C++17 only:
863 * using Members = folly::PolyMembers<
864 * folly::sig<int() const>(&T::Value),
865 * folly::sig<void(int)>(&T::Value)>;
868 * using IntProperty = Poly<IIntProperty>;
871 * Now, any object that has `Value` members of compatible signatures can be
872 * assigned to instances of `IntProperty` object. Note how `folly::sig` is used
873 * to disambiguate the overloads of `&T::Value`.
875 * \par Defining an interface with C++14
878 * In C++14, the nice syntax above doesn't work, so we have to resort to macros.
879 * The two examples above would look like this:
881 * template <class Value>
882 * struct IJavaIterator {
883 * template <class Base>
884 * struct Interface : Base {
885 * bool Done() const { return folly::poly_call<0>(*this); }
886 * Value Current() const { return folly::poly_call<1>(*this); }
887 * void Next() { folly::poly_call<2>(*this); }
889 * // NOTE: This works in C++14 and C++17:
891 * using Members = FOLLY_POLY_MEMBERS(&T::Done, &T::Current, &T::Next);
894 * template <class Value>
895 * using JavaIterator = Poly<IJavaIterator>;
900 * struct IIntProperty {
901 * template <class Base>
902 * struct Interface : Base {
903 * int Value() const { return folly::poly_call<0>(*this); }
904 * void Value(int i) { return folly::poly_call<1>(*this, i); }
906 * // NOTE: This works in C++14 and C++17:
908 * using Members = FOLLY_POLY_MEMBERS(
909 * FOLLY_POLY_MEMBER(int() const, &T::Value),
910 * FOLLY_POLY_MEMBER(void(int), &T::Value));
913 * using IntProperty = Poly<IIntProperty>;
915 * \par Extending interfaces
918 * One typical advantage of inheritance-based solutions to runtime polymorphism
919 * is that one polymorphic interface could extend another through inheritance.
920 * The same can be accomplished with type-erasing polymorphic wrappers. In
921 * the `Poly` library, you can use `folly::PolyExtends` to say that one
922 * interface extends another.
925 * template <class Base>
926 * struct Interface : Base {
927 * void Foo() const { return folly::poly_call<0>(*this); }
930 * using Members = FOLLY_POLY_MEMBERS(&T::Foo);
933 * // The IFooBar interface extends the IFoo interface
934 * struct IFooBar : PolyExtends<IFoo> {
935 * template <class Base>
936 * struct Interface : Base {
937 * void Bar() const { return folly::poly_call<0>(*this); }
940 * using Members = FOLLY_POLY_MEMBERS(&T::Bar);
943 * using FooBar = Poly<IFooBar>;
946 * Given the above defintion, instances of type `FooBar` have both `Foo()` and
947 * `Bar()` member functions.
950 * The sensible conversions exist between a wrapped derived type and a wrapped
951 * base type. For instance, assuming `IDerived` extends `IBase` with
954 * Poly<IDerived> derived = ...;
955 * Poly<IBase> base = derived; // This conversion is OK.
958 * As you would expect, there is no conversion in the other direction, and at
959 * present there is no `Poly` equivalent to `dynamic_cast`.
961 * \par Type-erasing polymorphic reference wrappers
964 * Sometimes you don't need to own a copy of an object; a reference will do. For
965 * that you can use `Poly` to capture a _reference_ to an object satisfying an
966 * interface rather than the whole object itself. The syntax is intuitive.
969 * // Capture a mutable reference to an object of any IRegular type:
970 * Poly<IRegular &> intRef = i;
971 * assert(42 == folly::poly_cast<int>(intRef));
972 * // Assert that we captured the address of "i":
973 * assert(&i == &folly::poly_cast<int>(intRef));
976 * A reference-like `Poly` has a different interface than a value-like `Poly`.
977 * Rather than calling member functions with the `obj.fun()` syntax, you would
978 * use the `obj->fun()` syntax. This is for the sake of `const`-correctness.
979 * For example, consider the code below:
982 * template <class Base>
984 * void Foo() { folly::poly_call<0>(*this); }
987 * using Members = folly::PolyMembers<&T::Foo>;
991 * void Foo() { std::printf("SomeFoo::Foo\n"); }
995 * Poly<IFoo &> const anyFoo = foo;
996 * anyFoo->Foo(); // prints "SomeFoo::Foo"
999 * Notice in the above code that the `Foo` member function is non-`const`.
1000 * Notice also that the `anyFoo` object is `const`. However, since it has
1001 * captured a non-`const` reference to the `foo` object, it should still be
1002 * possible to dispatch to the non-`const` `Foo` member function. When
1003 * instantiated with a reference type, `Poly` has an overloaded `operator->`
1004 * member that returns a pointer to the `IFoo` interface with the correct
1005 * `const`-ness, which makes this work.
1008 * The same mechanism also prevents users from calling non-`const` member
1009 * functions on `Poly` objects that have captured `const` references, which
1010 * would violate `const`-correctness.
1013 * Sensible conversions exist between non-reference and reference `Poly`s. For
1016 * Poly<IRegular> value = 42;
1017 * Poly<IRegular &> mutable_ref = value;
1018 * Poly<IRegular const &> const_ref = mutable_ref;
1020 * assert(&poly_cast<int>(value) == &poly_cast<int>(mutable_ref));
1021 * assert(&poly_cast<int>(value) == &poly_cast<int>(const_ref));
1023 * \par Non-member functions (C++17)
1026 * If you wanted to write the interface `ILogicallyNegatable`, which captures
1027 * all types that can be negated with unary `operator!`, you could do it
1028 * as we've shown above, by binding `&T::operator!` in the nested `Members`
1029 * alias template, but that has the problem that it won't work for types that
1030 * have defined unary `operator!` as a free function. To handle this case,
1031 * the `Poly` library lets you use a free function instead of a member function
1032 * when creating a binding.
1035 * With C++17 you may use a lambda to create a binding, as shown in the example
1038 * struct ILogicallyNegatable {
1039 * template <class Base>
1040 * struct Interface : Base {
1041 * bool operator!() const { return folly::poly_call<0>(*this); }
1043 * template <class T>
1044 * using Members = folly::PolyMembers<
1045 * +[](T const& t) -> decltype(!t) { return !t; }>;
1049 * This requires some explanation. The unary `operator+` in front of the lambda
1050 * is necessary! It causes the lambda to decay to a C-style function pointer,
1051 * which is one of the types that `folly::PolyMembers` accepts. The `decltype`
1052 * in the lambda return type is also necessary. Through the magic of SFINAE, it
1053 * will cause `Poly<ILogicallyNegatable>` to reject any types that don't support
1054 * unary `operator!`.
1057 * If you are using a free function to create a binding, the first parameter is
1058 * implicitly the `this` parameter. It will receive the type-erased object.
1060 * \par Non-member functions (C++14)
1063 * If you are using a C++14 compiler, the defintion of `ILogicallyNegatable`
1064 * above will fail because lambdas are not `constexpr`. We can get the same
1065 * effect by writing the lambda as a named free function, as show below:
1067 * struct ILogicallyNegatable {
1068 * template <class Base>
1069 * struct Interface : Base {
1070 * bool operator!() const { return folly::poly_call<0>(*this); }
1073 * template <class T>
1074 * static auto negate(T const& t) -> decltype(!t) { return !t; }
1076 * template <class T>
1077 * using Members = FOLLY_POLY_MEMBERS(&negate<T>);
1081 * As with the example that uses the lambda in the preceding section, the first
1082 * parameter is implicitly the `this` parameter. It will receive the type-erased
1085 * \par Multi-dispatch
1088 * What if you want to create an `IAddable` interface for things that can be
1089 * added? Adding requires _two_ objects, both of which are type-erased. This
1090 * interface requires dispatching on both objects, doing the addition only
1091 * if the types are the same. For this we make use of the `PolySelf` template
1092 * alias to define an interface that takes more than one object of the the
1096 * template <class Base>
1097 * struct Interface : Base {
1098 * friend PolySelf<Base, Decay>
1099 * operator+(PolySelf<Base> const& a, PolySelf<Base> const& b) {
1100 * return folly::poly_call<0, IAddable>(a, b);
1104 * template <class T>
1105 * using Members = folly::PolyMembers<
1106 * +[](T const& a, T const& b) -> decltype(a + b) { return a + b; }>;
1110 * Given the above defintion of `IAddable` we would be able to do the following:
1112 * Poly<IAddable> a = 2, b = 3;
1113 * Poly<IAddable> c = a + b;
1114 * assert(poly_cast<int>(c) == 5);
1117 * If `a` and `b` stored objects of different types, a `BadPolyCast` exception
1120 * \par Move-only types
1123 * If you want to store move-only types, then your interface should extend the
1124 * `IMoveOnly` interface.
1126 * \par Implementation notes
1128 * `Poly` will store "small" objects in an internal buffer, avoiding the cost of
1129 * of dynamic allocations. At present, this size is not configurable; it is
1130 * pegged at the size of two `double`s.
1133 * `Poly` objects are always nothrow movable. If you store an object in one that
1134 * has a potentially throwing move contructor, the object will be stored on the
1135 * heap, even if it could fit in the internal storage of the `Poly` object.
1136 * (So be sure to give your objects nothrow move constructors!)
1139 * `Poly` implements type-erasure in a manner very similar to how the compiler
1140 * accomplishes virtual dispatch. Every `Poly` object contains a pointer to a
1141 * table of function pointers. Member function calls involve a double-
1142 * indirection: once through the v-pointer, and other indirect function call
1143 * through the function pointer.
1146 struct Poly final : detail::PolyValOrRef<I> {
1147 friend detail::PolyAccess;
1149 using detail::PolyValOrRef<I>::PolyValOrRef;
1150 using detail::PolyValOrRef<I>::operator=;
1154 * Swap two `Poly<I>` instances.
1157 void swap(Poly<I>& left, Poly<I>& right) noexcept {
1162 * Pseudo-function template handy for disambiguating function overloads.
1164 * For example, given:
1166 * int property() const;
1167 * void property(int);
1170 * You can get a member function pointer to the first overload with:
1171 * folly::sig<int()const>(&S::property);
1173 * This is arguably a nicer syntax that using the built-in `static_cast`:
1174 * static_cast<int (S::*)() const>(&S::property);
1176 * `sig` is also more permissive than `static_cast` about `const`. For instance,
1177 * the following also works:
1178 * folly::sig<int()>(&S::property);
1180 * The above is permitted
1182 template <class Sig>
1183 FOLLY_INLINE_CONSTEXPR detail::Sig<Sig> const sig = {};
1185 } // namespace folly
1187 #include <folly/Poly-inl.h>
1189 #undef FOLLY_INLINE_CONSTEXPR