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