Poly.h 38 KB

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