🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

978 lines
38 KiB

  1. # Crash Course: runtime reflection system
  2. <!--
  3. @cond TURN_OFF_DOXYGEN
  4. -->
  5. # Table of Contents
  6. * [Introduction](#introduction)
  7. * [Names and identifiers](#names-and-identifiers)
  8. * [Reflection in a nutshell](#reflection-in-a-nutshell)
  9. * [Any to the rescue](#any-to-the-rescue)
  10. * [Enjoy the runtime](#enjoy-the-runtime)
  11. * [Container support](#container-support)
  12. * [Pointer-like types](#pointer-like-types)
  13. * [Template information](#template-information)
  14. * [Automatic conversions](#automatic-conversions)
  15. * [Implicitly generated default constructor](#implicitly-generated-default-constructor)
  16. * [Policies: the more, the less](#policies-the-more-the-less)
  17. * [Named constants and enums](#named-constants-and-enums)
  18. * [Properties and meta objects](#properties-and-meta-objects)
  19. * [Unregister types](#unregister-types)
  20. <!--
  21. @endcond TURN_OFF_DOXYGEN
  22. -->
  23. # Introduction
  24. Reflection (or rather, its lack) is a trending topic in the C++ world and a tool
  25. that can unlock a lot of interesting feature in the specific case of `EnTT`. I
  26. looked for a third-party library that met my needs on the subject, but I always
  27. came across some details that I didn't like: macros, being intrusive, too many
  28. allocations, and so on.<br/>
  29. I finally decided to write a built-in, non-intrusive and macro-free runtime
  30. reflection system for `EnTT`. Maybe I didn't do better than others or maybe yes,
  31. time will tell me, but at least I can model this tool around the library to
  32. which it belongs and not the opposite.
  33. # Names and identifiers
  34. The meta system doesn't force users to rely on the tools provided by the library
  35. when it comes to working with names and identifiers. It does this by offering an
  36. API that works with opaque identifiers that may or may not be generated by means
  37. of a hashed string.<br/>
  38. This means that users can assign any type of identifier to the meta objects, as
  39. long as they are numeric. It doesn't matter if they are generated at runtime, at
  40. compile-time or with custom functions.
  41. That being said, the examples in the following sections are all based on the
  42. `hashed_string` class as provided by this library. Therefore, where an
  43. identifier is required, it's likely that an user defined literal is used as
  44. follows:
  45. ```cpp
  46. auto factory = entt::meta<my_type>().type("reflected_type"_hs);
  47. ```
  48. For what it's worth, this is likely completely equivalent to:
  49. ```cpp
  50. auto factory = entt::meta<my_type>().type(42);
  51. ```
  52. Obviously, human-readable identifiers are more convenient to use and highly
  53. recommended.
  54. # Reflection in a nutshell
  55. Reflection always starts from real types (users cannot reflect imaginary types
  56. and it would not make much sense, we wouldn't be talking about reflection
  57. anymore).<br/>
  58. To create a meta node, the library provides the `meta` function that accepts a
  59. type to reflect as a template parameter:
  60. ```cpp
  61. auto factory = entt::meta<my_type>();
  62. ```
  63. This isn't enough to _export_ the given type and make it visible though.<br/>
  64. The returned value is a factory object to use to continue building the meta
  65. type. In order to make the type _visible_, users can assign it an identifier:
  66. ```cpp
  67. auto factory = entt::meta<my_type>().type("reflected_type"_hs);
  68. ```
  69. Or use the default one, that is, the built-in identifier for the given type:
  70. ```cpp
  71. auto factory = entt::meta<my_type>().type();
  72. ```
  73. Identifiers are important because users can retrieve meta types at runtime by
  74. searching for them by _name_ other than by type.<br/>
  75. On the other hand, there are cases in which users can be interested in adding
  76. features to a reflected type so that the reflection system can use it correctly
  77. under the hood, but they don't want to also make the type _searchable_. In this
  78. case, it's sufficient not to invoke `type`.
  79. A factory is such that all its member functions return the factory itself or a
  80. decorated version of it. This object can be used to add the following:
  81. * _Constructors_. Actual constructors can be assigned to a reflected type by
  82. specifying their list of arguments. Free functions (namely, factories) can be
  83. used as well, as long as the return type is the expected one. From a client's
  84. point of view, nothing changes if a constructor is a free function or an
  85. actual constructor.<br/>
  86. Use the `ctor` member function for this purpose:
  87. ```cpp
  88. entt::meta<my_type>().ctor<int, char>().ctor<&factory>();
  89. ```
  90. * _Destructors_. Free functions and member functions can be used as destructors
  91. of reflected types. The purpose is to give users the ability to free up
  92. resources that require special treatment before an object is actually
  93. destroyed.<br/>
  94. Use the `dtor` member function for this purpose:
  95. ```cpp
  96. entt::meta<my_type>().dtor<&destroy>();
  97. ```
  98. A function should neither delete nor explicitly invoke the destructor of a
  99. given instance.
  100. * _Data members_. Both real data members of the underlying type and static and
  101. global variables, as well as constants of any kind, can be attached to a meta
  102. type. From the point of view of the client, all the variables associated with
  103. the reflected type will appear as if they were part of the type itself.<br/>
  104. Use the `data` member function for this purpose:
  105. ```cpp
  106. entt::meta<my_type>()
  107. .data<&my_type::static_variable>("static"_hs)
  108. .data<&my_type::data_member>("member"_hs)
  109. .data<&global_variable>("global"_hs);
  110. ```
  111. The function requires as an argument the identifier to give to the meta data
  112. once created. Users can then access meta data at runtime by searching for them
  113. by _name_.<br/>
  114. Data members can also be defined by means of a setter and getter pair. Setters
  115. and getters can be either free functions, class members or a mix of them, as
  116. long as they respect the required signatures. This approach is also convenient
  117. to create a read-only variable from a non-const data member:
  118. ```cpp
  119. entt::meta<my_type>().data<nullptr, &my_type::data_member>("member"_hs);
  120. ```
  121. Multiple setters are also supported by means of a `value_list` object:
  122. ```cpp
  123. entt::meta<my_type>().data<entt::value_list<&from_int, &from_string>, &my_type::data_member>("member"_hs);
  124. ```
  125. Refer to the inline documentation for all the details.
  126. * _Member functions_. Both real member functions of the underlying type and free
  127. functions can be attached to a meta type. From the point of view of the
  128. client, all the functions associated with the reflected type will appear as if
  129. they were part of the type itself.<br/>
  130. Use the `func` member function for this purpose:
  131. ```cpp
  132. entt::meta<my_type>()
  133. .func<&my_type::static_function>("static"_hs)
  134. .func<&my_type::member_function>("member"_hs)
  135. .func<&free_function>("free"_hs);
  136. ```
  137. The function requires as an argument the identifier to give to the meta
  138. function once created. Users can then access meta functions at runtime by
  139. searching for them by _name_.<br/>
  140. Overloading of meta functions is supported. Overloaded functions are resolved
  141. at runtime by the reflection system according to the types of the arguments.
  142. * _Base classes_. A base class is such that the underlying type is actually
  143. derived from it. In this case, the reflection system tracks the relationship
  144. and allows for implicit casts at runtime when required.<br/>
  145. Use the `base` member function for this purpose:
  146. ```cpp
  147. entt::meta<derived_type>().base<base_type>();
  148. ```
  149. From now on, wherever a `base_type` is required, an instance of `derived_type`
  150. will also be accepted.
  151. * _Conversion functions_. Actual types can be converted, this is a fact. Just
  152. think of the relationship between a `double` and an `int` to see it. Similar
  153. to bases, conversion functions allow users to define conversions that will be
  154. implicitly performed by the reflection system when required.<br/>
  155. Use the `conv` member function for this purpose:
  156. ```cpp
  157. entt::meta<double>().conv<int>();
  158. ```
  159. That's all, everything users need to create meta types and enjoy the reflection
  160. system. At first glance it may not seem that much, but users usually learn to
  161. appreciate it over time.<br/>
  162. Also, do not forget what these few lines hide under the hood: a built-in,
  163. non-intrusive and macro-free system for reflection in C++. Features that are
  164. definitely worth the price, at least for me.
  165. ## Any to the rescue
  166. The reflection system offers a kind of _extended version_ of the `entt::any`
  167. class (see the core module for more details).<br/>
  168. The purpose is to add some feature on top of those already present, so as to
  169. integrate it with the meta type system without having to duplicate the code.
  170. The API is very similar to that of the `any` type. The class `meta_any` _wraps_
  171. many of the feature to infer a meta node, before forwarding some or all of the
  172. arguments to the underlying storage.<br/>
  173. Among the few relevant differences, `meta_any` adds support for containers and
  174. pointer-like types (see the following sections for more details), while `any`
  175. does not.<br/>
  176. Similar to `any`, this class can also be used to create _aliases_ for unmanaged
  177. objects either with `forward_as_meta` or using the `std::in_place_type<T &>`
  178. disambiguation tag, as well as from an existing object by means of the `as_ref`
  179. member function. However, unlike `any`, `meta_any` treats an empty instance and
  180. one initialized with `void` differently:
  181. ```cpp
  182. entt::meta_any empty{};
  183. entt::meta_any other{std::in_place_type<void>};
  184. ```
  185. While `any` considers both as empty, `meta_any` treats objects initialized with
  186. `void` as if they were _valid_ ones. This allows to differentiate between failed
  187. function calls and function calls that are successful but return nothing.<br/>
  188. Finally, the member functions `try_cast`, `cast` and `allow_cast` are used to
  189. cast the underlying object to a given type (either a reference or a value type)
  190. or to _convert_ a `meta_any` in such a way that a cast becomes viable for the
  191. resulting object. There is in fact no `any_cast` equivalent for `meta_any`.
  192. ## Enjoy the runtime
  193. Once the web of reflected types has been constructed, it's a matter of using it
  194. at runtime where required.<br/>
  195. All this has the great merit that the reflection system stands in fact as a
  196. non-intrusive tool for the runtime, unlike the vast majority of the things
  197. offered by this library and closely linked to the compile-time.
  198. To search for a reflected type there are a few options:
  199. ```cpp
  200. // direct access to a reflected type
  201. auto by_type = entt::resolve<my_type>();
  202. // look up a reflected type by identifier
  203. auto by_id = entt::resolve("reflected_type"_hs);
  204. // look up a reflected type by type info
  205. auto by_type_id = entt::resolve(entt::type_id<my_type>());
  206. ```
  207. There exits also an overload of the `resolve` function to use to iterate all the
  208. reflected types at once. It returns an iterable object that can be used in a
  209. range-for loop:
  210. ```cpp
  211. for(auto type: entt::resolve()) {
  212. // ...
  213. }
  214. ```
  215. In all cases, the returned value is an instance of `meta_type`. This kind of
  216. objects offer an API to know their _runtime identifiers_, to iterate all the
  217. meta objects associated with them and even to build instances of the underlying
  218. type.<br/>
  219. Refer to the inline documentation for all the details.
  220. The meta objects that compose a meta type are accessed in the following ways:
  221. * _Meta data_. They are accessed by _name_:
  222. ```cpp
  223. auto data = entt::resolve<my_type>().data("member"_hs);
  224. ```
  225. The returned type is `meta_data` and may be invalid if there is no meta data
  226. object associated with the given identifier.<br/>
  227. A meta data object offers an API to query the underlying type (for example, to
  228. know if it's a const or a static one), to get the meta type of the variable
  229. and to set or get the contained value.
  230. * _Meta functions_. They are accessed by _name_:
  231. ```cpp
  232. auto func = entt::resolve<my_type>().func("member"_hs);
  233. ```
  234. The returned type is `meta_func` and may be invalid if there is no meta
  235. function object associated with the given identifier.<br/>
  236. A meta function object offers an API to query the underlying type (for
  237. example, to know if it's a const or a static function), to know the number of
  238. arguments, the meta return type and the meta types of the parameters. In
  239. addition, a meta function object can be used to invoke the underlying function
  240. and then get the return value in the form of a `meta_any` object.
  241. * _Meta bases_. They are accessed through the _name_ of the base types:
  242. ```cpp
  243. auto base = entt::resolve<derived_type>().base("base"_hs);
  244. ```
  245. The returned type is `meta_type` and may be invalid if there is no meta base
  246. object associated with the given identifier.
  247. All the objects thus obtained as well as the meta types can be explicitly
  248. converted to a boolean value to check if they are valid:
  249. ```cpp
  250. if(auto func = entt::resolve<my_type>().func("member"_hs); func) {
  251. // ...
  252. }
  253. ```
  254. Furthermore, all them are also returned by specific overloads that provide the
  255. caller with iterable ranges of top-level elements. As an example:
  256. ```cpp
  257. for(auto data: entt::resolve<my_type>().data()) {
  258. // ...
  259. }
  260. ```
  261. A meta type can be used to `construct` actual instances of the underlying
  262. type.<br/>
  263. In particular, the `construct` member function accepts a variable number of
  264. arguments and searches for a match. It then returns a `meta_any` object that may
  265. or may not be initialized, depending on whether a suitable constructor has been
  266. found or not.
  267. There is no object that wraps the destructor of a meta type nor a `destroy`
  268. member function in its API. Destructors are invoked implicitly by `meta_any`
  269. behind the scenes and users have not to deal with them explicitly. Furthermore,
  270. they have no name, cannot be searched and wouldn't have member functions to
  271. expose anyway.<br/>
  272. Similarly, conversion functions aren't directly accessible. They are used
  273. internally by `meta_any` and the meta objects when needed.
  274. Meta types and meta objects in general contain much more than what is said: a
  275. plethora of functions in addition to those listed whose purposes and uses go
  276. unfortunately beyond the scope of this document.<br/>
  277. I invite anyone interested in the subject to look at the code, experiment and
  278. read the inline documentation to get the best out of this powerful tool.
  279. ## Container support
  280. The runtime reflection system also supports containers of all types.<br/>
  281. Moreover, _containers_ doesn't necessarily mean those offered by the C++
  282. standard library. In fact, user defined data structures can also work with the
  283. meta system in many cases.
  284. To make a container be recognized as such by the meta system, users are required
  285. to provide specializations for either the `meta_sequence_container_traits` class
  286. or the `meta_associative_container_traits` class, according with the actual type
  287. of the container.<br/>
  288. `EnTT` already exports the specializations for some common classes. In
  289. particular:
  290. * `std::vector` and `std::array` are exported as _sequence containers_.
  291. * `std::map`, `std::set` and their unordered counterparts are exported as
  292. _associative containers_.
  293. It's important to include the header file `container.hpp` to make these
  294. specializations available to the compiler when needed.<br/>
  295. The same file also contains many examples for the users that are interested in
  296. making their own containers available to the meta system.
  297. When a specialization of the `meta_sequence_container_traits` class exists, the
  298. meta system treats the wrapped type as a sequence container. In a similar way,
  299. a type is treated as an associative container if a specialization of the
  300. `meta_associative_container_traits` class is found for it.<br/>
  301. Proxy objects are returned by dedicated members of the `meta_any` class. The
  302. following is a deliberately verbose example of how users can access a proxy
  303. object for a sequence container:
  304. ```cpp
  305. std::vector<int> vec{1, 2, 3};
  306. entt::meta_any any = entt::forward_as_meta(vec);
  307. if(any.type().is_sequence_container()) {
  308. if(auto view = any.as_sequence_container(); view) {
  309. // ...
  310. }
  311. }
  312. ```
  313. The method to use to get a proxy object for associative containers is
  314. `as_associative_container` instead.<br/>
  315. It goes without saying that it's not necessary to perform a double check.
  316. Instead, it's sufficient to query the meta type or verify that the proxy object
  317. is valid. In fact, proxies are contextually convertible to bool to know if they
  318. are valid. For example, invalid proxies are returned when the wrapped object
  319. isn't a container.<br/>
  320. In all cases, users aren't expected to _reflect_ containers explicitly. It's
  321. sufficient to assign a container for which a specialization of the traits
  322. classes exists to a `meta_any` object to be able to get its proxy object.
  323. The interface of the `meta_sequence_container` proxy object is the same for all
  324. types of sequence containers, although the available features differ from case
  325. to case. In particular:
  326. * The `value_type` member function returns the meta type of the elements.
  327. * The `size` member function returns the number of elements in the container as
  328. an unsigned integer value:
  329. ```cpp
  330. const auto size = view.size();
  331. ```
  332. * The `resize` member function allows to resize the wrapped container and
  333. returns true in case of success:
  334. ```cpp
  335. const bool ok = view.resize(3u);
  336. ```
  337. For example, it's not possible to resize fixed size containers.
  338. * The `clear` member function allows to clear the wrapped container and returns
  339. true in case of success:
  340. ```cpp
  341. const bool ok = view.clear();
  342. ```
  343. For example, it's not possible to clear fixed size containers.
  344. * The `begin` and `end` member functions return opaque iterators that can be
  345. used to iterate the container directly:
  346. ```cpp
  347. for(entt::meta_any element: view) {
  348. // ...
  349. }
  350. ```
  351. In all cases, given an underlying container of type `C`, the returned element
  352. contains an object of type `C::value_type` which therefore depends on the
  353. actual container.<br/>
  354. All meta iterators are input iterators and don't offer an indirection operator
  355. on purpose.
  356. * The `insert` member function can be used to add elements to the container. It
  357. accepts a meta iterator and the element to insert:
  358. ```cpp
  359. auto last = view.end();
  360. // appends an integer to the container
  361. view.insert(last, 42);
  362. ```
  363. This function returns a meta iterator pointing to the inserted element and a
  364. boolean value to indicate whether the operation was successful or not. Note
  365. that a call to `insert` may silently fail in case of fixed size containers or
  366. whether the arguments aren't at least convertible to the required types.<br/>
  367. Since the meta iterators are contextually convertible to bool, users can rely
  368. on them to know if the operation has failed on the actual container or
  369. upstream, for example for an argument conversion problem.
  370. * The `erase` member function can be used to remove elements from the container.
  371. It accepts a meta iterator to the element to remove:
  372. ```cpp
  373. auto first = view.begin();
  374. // removes the first element from the container
  375. view.erase(first);
  376. ```
  377. This function returns a meta iterator following the last removed element and a
  378. boolean value to indicate whether the operation was successful or not. Note
  379. that a call to `erase` may silently fail in case of fixed size containers.
  380. * The `operator[]` can be used to access elements in a container. It accepts a
  381. single argument, that is the position of the element to return:
  382. ```cpp
  383. for(std::size_t pos{}, last = view.size(); pos < last; ++pos) {
  384. entt::meta_any value = view[pos];
  385. // ...
  386. }
  387. ```
  388. The function returns instances of `meta_any` that directly refer to the actual
  389. elements. Modifying the returned object will then directly modify the element
  390. inside the container.
  391. Similarly, also the interface of the `meta_associative_container` proxy object
  392. is the same for all types of associative containers. However, there are some
  393. differences in behavior in the case of key-only containers. In particular:
  394. * The `key_only` member function returns true if the wrapped container is a
  395. key-only one.
  396. * The `key_type` member function returns the meta type of the keys.
  397. * The `mapped_type` member function returns an invalid meta type for key-only
  398. containers and the meta type of the mapped values for all other types of
  399. containers.
  400. * The `value_type` member function returns the meta type of the elements.<br/>
  401. For example, it returns the meta type of `int` for `std::set<int>` while it
  402. returns the meta type of `std::pair<const int, char>` for
  403. `std::map<int, char>`.
  404. * The `size` member function returns the number of elements in the container as
  405. an unsigned integer value:
  406. ```cpp
  407. const auto size = view.size();
  408. ```
  409. * The `clear` member function allows to clear the wrapped container and returns
  410. true in case of success:
  411. ```cpp
  412. const bool ok = view.clear();
  413. ```
  414. * The `begin` and `end` member functions return opaque iterators that can be
  415. used to iterate the container directly:
  416. ```cpp
  417. for(std::pair<entt::meta_any, entt::meta_any> element: view) {
  418. // ...
  419. }
  420. ```
  421. In all cases, given an underlying container of type `C`, the returned element
  422. is a key-value pair where the key has type `C::key_type` and the value has
  423. type `C::mapped_type`. Since key-only containers don't have a mapped type,
  424. their _value_ is nothing more than an invalid `meta_any` object.<br/>
  425. All meta iterators are input iterators and don't offer an indirection operator
  426. on purpose.
  427. While the accessed key is usually constant in the associative containers and
  428. is therefore returned by copy, the value (if any) is wrapped by an instance of
  429. `meta_any` that directly refers to the actual element. Modifying it will then
  430. directly modify the element inside the container.
  431. * The `insert` member function can be used to add elements to the container. It
  432. accepts two arguments, respectively the key and the value to be inserted:
  433. ```cpp
  434. auto last = view.end();
  435. // appends an integer to the container
  436. view.insert(last.handle(), 42, 'c');
  437. ```
  438. This function returns a boolean value to indicate whether the operation was
  439. successful or not. Note that a call to `insert` may fail when the arguments
  440. aren't at least convertible to the required types.
  441. * The `erase` member function can be used to remove elements from the container.
  442. It accepts a single argument, that is the key to be removed:
  443. ```cpp
  444. view.erase(42);
  445. ```
  446. This function returns a boolean value to indicate whether the operation was
  447. successful or not. Note that a call to `erase` may fail when the argument
  448. isn't at least convertible to the required type.
  449. * The `operator[]` can be used to access elements in a container. It accepts a
  450. single argument, that is the key of the element to return:
  451. ```cpp
  452. entt::meta_any value = view[42];
  453. ```
  454. The function returns instances of `meta_any` that directly refer to the actual
  455. elements. Modifying the returned object will then directly modify the element
  456. inside the container.
  457. Container support is minimal but likely sufficient to satisfy all needs.
  458. ## Pointer-like types
  459. As with containers, it's also possible to communicate to the meta system which
  460. types to consider _pointers_. This will allow to dereference instances of
  461. `meta_any`, thus obtaining light _references_ to the pointed objects that are
  462. also correctly associated with their meta types.<br/>
  463. To make the meta system recognize a type as _pointer-like_, users can specialize
  464. the `is_meta_pointer_like` class. `EnTT` already exports the specializations for
  465. some common classes. In particular:
  466. * All types of raw pointers.
  467. * `std::unique_ptr` and `std::shared_ptr`.
  468. It's important to include the header file `pointer.hpp` to make these
  469. specializations available to the compiler when needed.<br/>
  470. The same file also contains many examples for the users that are interested in
  471. making their own pointer-like types available to the meta system.
  472. When a type is recognized as a pointer-like one by the meta system, it's
  473. possible to dereference the instances of `meta_any` that contain these objects.
  474. The following is a deliberately verbose example to show how to use this feature:
  475. ```cpp
  476. int value = 42;
  477. // meta type equivalent to that of int *
  478. entt::meta_any any{&value};
  479. if(any.type().is_pointer_like()) {
  480. // meta type equivalent to that of int
  481. if(entt::meta_any ref = *any; ref) {
  482. // ...
  483. }
  484. }
  485. ```
  486. Of course, it's not necessary to perform a double check. Instead, it's enough to
  487. query the meta type or verify that the returned object is valid. For example,
  488. invalid instances are returned when the wrapped object isn't a pointer-like
  489. type.<br/>
  490. Note that dereferencing a pointer-like object returns an instance of `meta_any`
  491. which refers to the pointed object and allows users to modify it directly
  492. (unless the returned element is const, of course).
  493. In general, _dereferencing_ a pointer-like type boils down to a `*ptr`. However,
  494. `EnTT` also supports classes that don't offer an `operator*`. In particular:
  495. * It's possible to exploit a solution based on ADL lookup by offering a function
  496. (also a template one) named `dereference_meta_pointer_like`:
  497. ```cpp
  498. template<typename Type>
  499. Type & dereference_meta_pointer_like(const custom_pointer_type<Type> &ptr) {
  500. return ptr.deref();
  501. }
  502. ```
  503. * When not in control of the type's namespace, it's possible to inject into the
  504. `entt` namespace a specialization of the `adl_meta_pointer_like` class
  505. template to bypass the adl lookup as a whole:
  506. ```cpp
  507. template<typename Type>
  508. struct entt::adl_meta_pointer_like<custom_pointer_type<Type>> {
  509. static decltype(auto) dereference(const custom_pointer_type<Type> &ptr) {
  510. return ptr.deref();
  511. }
  512. };
  513. ```
  514. In all other cases, that is, when dereferencing a pointer works as expected and
  515. regardless of the pointed type, no user intervention is required.
  516. ## Template information
  517. Meta types also provide a minimal set of information about the nature of the
  518. original type in case it's a class template.<br/>
  519. By default, this works out of the box and requires no user action. However, it's
  520. important to include the header file `template.hpp` to make these information
  521. available to the compiler when needed.
  522. Meta template information are easily found:
  523. ```cpp
  524. // this method returns true if the type is recognized as a class template specialization
  525. if(auto type = entt::resolve<std::shared_ptr<my_type>>(); type.is_template_specialization()) {
  526. // meta type of the class template conveniently wrapped by entt::meta_class_template_tag
  527. auto class_type = type.template_type();
  528. // number of template arguments
  529. std::size_t arity = type.template_arity();
  530. // meta type of the i-th argument
  531. auto arg_type = type.template_arg(0u);
  532. }
  533. ```
  534. Typically, when template information for a type are required, what the library
  535. provides is sufficient. However, there are some cases where a user may want more
  536. details or a different set of information.<br/>
  537. Consider the case of a class template that is meant to wrap function types:
  538. ```cpp
  539. template<typename>
  540. struct function_type;
  541. template<typename Ret, typename... Args>
  542. struct function_type<Ret(Args...)> {};
  543. ```
  544. In this case, rather than the function type, the user might want the return type
  545. and unpacked arguments as if they were different template parameters for the
  546. original class template.<br/>
  547. To achieve this, users must enter the library internals and provide their own
  548. specialization for the class template `entt::meta_template_traits`, such as:
  549. ```cpp
  550. template<typename Ret, typename... Args>
  551. struct entt::meta_template_traits<function_type<Ret(Args...)>> {
  552. using class_type = meta_class_template_tag<function_type>;
  553. using args_type = type_list<Ret, Args...>;
  554. };
  555. ```
  556. The reflection system doesn't verify the accuracy of the information nor infer a
  557. correspondence between real types and meta types.<br/>
  558. Therefore, the specialization will be used as is and the information it contains
  559. will be associated with the appropriate type when required.
  560. ## Automatic conversions
  561. In C++, there are a number of conversions allowed between arithmetic types that
  562. make it convenient to work with this kind of data.<br/>
  563. If this were to be translated into explicit registrations with the reflection
  564. system, it would result in a long series of instructions such as the following:
  565. ```cpp
  566. entt::meta<int>()
  567. .conv<bool>()
  568. .conv<char>()
  569. // ...
  570. .conv<double>();
  571. ```
  572. Repeated for each type eligible to undergo this type of conversions. This is
  573. both error prone and repetitive.<br/>
  574. Similarly, the language allows users to silently convert unscoped enums to their
  575. underlying types and offers what it takes to do the same for scoped enums. It
  576. would result in the following if it were to be done explicitly:
  577. ```cpp
  578. entt::meta<my_enum>()
  579. .conv<std::underlying_type_t<my_enum>>();
  580. ```
  581. Fortunately, all of this can also be avoided. `EnTT` offers implicit support for
  582. these types of conversions:
  583. ```cpp
  584. entt::meta_any any{42};
  585. any.allow_cast<double>();
  586. double value = any.cast<double>();
  587. ```
  588. With no need for registration, the conversion takes place automatically under
  589. the hood. The same goes for a call to `allow_cast` involving a meta type:
  590. ```cpp
  591. entt::meta_type type = entt::resolve<int>();
  592. entt::meta_any any{my_enum::a_value};
  593. any.allow_cast(type);
  594. int value = any.cast<int>();
  595. ```
  596. This should make working with arithmetic types and scoped or unscoped enums as
  597. easy as it is in C++.<br/>
  598. It's also worth noting that it's still possible to set up conversion functions
  599. manually and these will always be preferred over the automatic ones.
  600. ## Implicitly generated default constructor
  601. In many cases, it's useful to be able to create objects of default constructible
  602. types through the reflection system, while not having to explicitly register the
  603. meta type or the default constructor.<br/>
  604. For example, in the case of primitive types like `int` or `char`, but not just
  605. them.
  606. For this reason and only for default constructible types, default constructors
  607. are automatically defined and associated with their meta types, whether they are
  608. explicitly or implicitly generated.<br/>
  609. Therefore, this is all is needed to construct an integer from its meta type:
  610. ```cpp
  611. entt::resolve<int>().construct();
  612. ```
  613. Where the meta type can be for example the one returned from a meta container,
  614. useful for building keys without knowing or having to register the actual types.
  615. In all cases, when users register default constructors, they are preferred both
  616. during searches and when the `construct` member function is invoked.
  617. ## Policies: the more, the less
  618. Policies are a kind of compile-time directives that can be used when registering
  619. reflection information.<br/>
  620. Their purpose is to require slightly different behavior than the default in some
  621. specific cases. For example, when reading a given data member, its value is
  622. returned wrapped in a `meta_any` object which, by default, makes a copy of it.
  623. For large objects or if the caller wants to access the original instance, this
  624. behavior isn't desirable. Policies are there to offer a solution to this and
  625. other problems.
  626. There are a few alternatives available at the moment:
  627. * The _as-is_ policy, associated with the type `entt::as_is_t`.<br/>
  628. This is the default policy. In general, it should never be used explicitly,
  629. since it's implicitly selected if no other policy is specified.<br/>
  630. In this case, the return values of the functions as well as the properties
  631. exposed as data members are always returned by copy in a dedicated wrapper and
  632. therefore associated with their original meta types.
  633. * The _as-void_ policy, associated with the type `entt::as_void_t`.<br/>
  634. Its purpose is to discard the return value of a meta object, whatever it is,
  635. thus making it appear as if its type were `void`:
  636. ```cpp
  637. entt::meta<my_type>().func<&my_type::member_function, entt::as_void_t>("member"_hs);
  638. ```
  639. If the use with functions is obvious, it must be said that it's also possible
  640. to use this policy with constructors and data members. In the first case, the
  641. constructor will be invoked but the returned wrapper will actually be empty.
  642. In the second case, instead, the property will not be accessible for reading.
  643. * The _as-ref_ and _as-cref_ policies, associated with the types
  644. `entt::as_ref_t` and `entt::as_cref_t`.<br/>
  645. They allow to build wrappers that act as references to unmanaged objects.
  646. Accessing the object contained in the wrapper for which the _reference_ was
  647. requested will make it possible to directly access the instance used to
  648. initialize the wrapper itself:
  649. ```cpp
  650. entt::meta<my_type>().data<&my_type::data_member, entt::as_ref_t>("member"_hs);
  651. ```
  652. These policies work with constructors (for example, when objects are taken
  653. from an external container rather than created on demand), data members and
  654. functions in general.<br/>
  655. If on the one hand `as_cref_t` always forces the return type to be const,
  656. `as_ref_t` _adapts_ to the constness of the passed object and to that of the
  657. return type if any.
  658. Some uses are rather trivial, but it's useful to note that there are some less
  659. obvious corner cases that can in turn be solved with the use of policies.
  660. ## Named constants and enums
  661. A special mention should be made for constant values and enums. It wouldn't be
  662. necessary, but it will help distracted readers.
  663. As mentioned, the `data` member function can be used to reflect constants of any
  664. type among the other things.<br/>
  665. This allows users to create meta types for enums that will work exactly like any
  666. other meta type built from a class. Similarly, arithmetic types can be enriched
  667. with constants of special meaning where required.<br/>
  668. Personally, I find it very useful not to export what is the difference between
  669. enums and classes in C++ directly in the space of the reflected types.
  670. All the values thus exported will appear to users as if they were constant data
  671. members of the reflected types.
  672. Exporting constant values or elements from an enum is as simple as ever:
  673. ```cpp
  674. entt::meta<my_enum>()
  675. .data<my_enum::a_value>("a_value"_hs)
  676. .data<my_enum::another_value>("another_value"_hs);
  677. entt::meta<int>().data<2048>("max_int"_hs);
  678. ```
  679. It goes without saying that accessing them is trivial as well. It's a matter of
  680. doing the following, as with any other data member of a meta type:
  681. ```cpp
  682. auto value = entt::resolve<my_enum>().data("a_value"_hs).get({}).cast<my_enum>();
  683. auto max = entt::resolve<int>().data("max_int"_hs).get({}).cast<int>();
  684. ```
  685. As a side note, remember that all this happens behind the scenes without any
  686. allocation because of the small object optimization performed by the `meta_any`
  687. class.
  688. ## Properties and meta objects
  689. Sometimes (for example, when it comes to creating an editor) it might be useful
  690. to attach properties to the meta objects created. Fortunately, this is possible
  691. for most of them.<br/>
  692. For the meta objects that support properties, the member functions of the
  693. factory used for registering them will return a decorated version of the factory
  694. itself. The latter can be used to attach properties to the last created meta
  695. object.<br/>
  696. Apparently, it's more difficult to say than to do:
  697. ```cpp
  698. entt::meta<my_type>().type("reflected_type"_hs).prop("tooltip"_hs, "message");
  699. ```
  700. Properties are always in the key/value form. There are no restrictions on the
  701. type of the key or value, as long as they are copy constructible objects.<br/>
  702. Multiple formats are supported when it comes to defining a property:
  703. * Properties as key/value pairs:
  704. ```cpp
  705. entt::meta<my_type>().type("reflected_type"_hs).prop("tooltip"_hs, "message");
  706. ```
  707. * Properties as `std::pair`s:
  708. ```cpp
  709. entt::meta<my_type>().type("reflected_type"_hs).prop(std::make_pair("tooltip"_hs, "message"));
  710. ```
  711. * Key only properties:
  712. ```cpp
  713. entt::meta<my_type>().type("reflected_type"_hs).prop(my_enum::key_only);
  714. ```
  715. * Properties as `std::tuple`s:
  716. ```cpp
  717. entt::meta<my_type>().type("reflected_type"_hs).prop(std::make_tuple(std::make_pair("tooltip"_hs, "message"), my_enum::key_only));
  718. ```
  719. A tuple contains one or more properties. All of them are treated individually.
  720. Note that it's not possible to invoke `prop` multiple times for the same meta
  721. object and trying to do that will result in a compilation error.<br/>
  722. However, the `props` function is available to associate several properties at
  723. once. In this case, properties in the key/value form aren't allowed, since they
  724. would be interpreted as two different properties rather than a single one.
  725. The meta objects for which properties are supported are currently meta types,
  726. meta data and meta functions.<br/>
  727. These types also offer a couple of member functions named `prop` to iterate all
  728. properties at once or to search a specific property by key:
  729. ```cpp
  730. // iterate all properties of a meta type
  731. for(auto prop: entt::resolve<my_type>().prop()) {
  732. // ...
  733. }
  734. // search for a given property by name
  735. auto prop = entt::resolve<my_type>().prop("tooltip"_hs);
  736. ```
  737. Meta properties are objects having a fairly poor interface, all in all. They
  738. only provide the `key` and the `value` member functions to be used to retrieve
  739. the key and the value contained in the form of `meta_any` objects, respectively.
  740. ## Unregister types
  741. A type registered with the reflection system can also be unregistered. This
  742. means unregistering all its data members, member functions, conversion functions
  743. and so on. However, base classes aren't unregistered as well, since they don't
  744. necessarily depend on it. Similarly, implicitly generated types (as an example,
  745. the meta types implicitly generated for function parameters when needed) aren't
  746. unregistered.<br/>
  747. Roughly speaking, unregistering a type means disconnecting all associated meta
  748. objects from it and making its identifier no longer visible. The underlying node
  749. will remain available though, as if it were implicitly generated:
  750. ```cpp
  751. entt::meta_reset<my_type>();
  752. ```
  753. It's also possible to reset types by their unique identifiers if required:
  754. ```cpp
  755. entt::meta_reset("my_type"_hs);
  756. ```
  757. Finally, there exists a non-template overload of the `meta_reset` function that
  758. doesn't accept argument and resets all searchable types (that is, all types that
  759. were assigned an unique identifier):
  760. ```cpp
  761. entt::meta_reset();
  762. ```
  763. All types can be re-registered later with a completely different name and form.