🛠️🐜 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.

414 lines
16 KiB

  1. # Crash Course: reflection system
  2. <!--
  3. @cond TURN_OFF_DOXYGEN
  4. -->
  5. # Table of Contents
  6. * [Introduction](#introduction)
  7. * [Reflection in a nutshell](#reflection-in-a-nutshell)
  8. * [Any as in any type](#any-as-in-any-type)
  9. * [Enjoy the runtime](#enjoy-the-runtime)
  10. * [Named constants and enums](#named-constants-and-enums)
  11. * [Properties and meta objects](#properties-and-meta-objects)
  12. * [Unregister types](#unregister-types)
  13. <!--
  14. @endcond TURN_OFF_DOXYGEN
  15. -->
  16. # Introduction
  17. Reflection (or rather, its lack) is a trending topic in the C++ world and, in
  18. the specific case of `EnTT`, a tool that can unlock a lot of other features. I
  19. looked for a third-party library that met my needs on the subject, but I always
  20. came across some details that I didn't like: macros, being intrusive, too many
  21. allocations. In one word: unsatisfactory.<br/>
  22. I finally decided to write a built-in, non-intrusive and macro-free runtime
  23. reflection system for `EnTT`. Maybe I didn't do better than others or maybe yes,
  24. time will tell me, but at least I can model this tool around the library to
  25. which it belongs and not vice versa.
  26. # Reflection in a nutshell
  27. Reflection always starts from real types (users cannot reflect imaginary types
  28. and it would not make much sense, we wouldn't be talking about reflection
  29. anymore).<br/>
  30. To _reflect_ a type, the library provides the `reflect` function:
  31. ```cpp
  32. auto factory = entt::reflect<my_type>("reflected_type");
  33. ```
  34. It accepts the type to reflect as a template parameter and an optional name as
  35. an argument. Names are important because users can retrieve meta types at
  36. runtime by searching for them by name. However, there are cases in which users
  37. can be interested in adding features to a reflected type so that the reflection
  38. system can use it correctly under the hood, but they don't want to allow
  39. searching the type by name.<br/>
  40. In both cases, the returned value is a factory object to use to continue
  41. building the meta type.
  42. A factory is such that all its member functions returns the factory itself.
  43. It can be used to extend the reflected type and add the following:
  44. * _Constructors_. Actual constructors can be assigned to a reflected type by
  45. specifying their list of arguments. Free functions (namely, factories) can be
  46. used as well, as long as the return type is the expected one. From a client's
  47. point of view, nothing changes if a constructor is a free function or an
  48. actual constructor.<br/>
  49. Use the `ctor` member function for this purpose:
  50. ```cpp
  51. entt::reflect<my_type>("reflected").ctor<int, char>().ctor<&factory>();
  52. ```
  53. * _Destructors_. Free functions can be set as destructors of reflected types.
  54. The purpose is to give users the ability to free up resources that require
  55. special treatment before an object is actually destroyed.<br/>
  56. Use the `dtor` member function for this purpose:
  57. ```cpp
  58. entt::reflect<my_type>("reflected").dtor<&destroy>();
  59. ```
  60. * _Data members_. Both real data members of the underlying type and static and
  61. global variables, as well as constants of any kind, can be attached to a meta
  62. type. From a client's point of view, all the variables associated with the
  63. reflected type will appear as if they were part of the type itself.<br/>
  64. Use the `data` member function for this purpose:
  65. ```cpp
  66. entt::reflect<my_type>("reflected")
  67. .data<&my_type::static_variable>("static")
  68. .data<&my_type::data_member>("member")
  69. .data<&global_variable>("global");
  70. ```
  71. This function requires as an argument the name to give to the meta data once
  72. created. Users can then access meta data at runtime by searching for them by
  73. name.<br/>
  74. Data members can be set also by means of a couple of functions, namely a
  75. setter and a getter. Setters and getters can be either free functions, member
  76. functions or mixed ones, as long as they respect the required signatures.<br/>
  77. Refer to the inline documentation for all the details.
  78. * _Member functions_. Both real member functions of the underlying type and free
  79. functions can be attached to a meta type. From a client's point of view, all
  80. the functions associated with the reflected type will appear as if they were
  81. part of the type itself.<br/>
  82. Use the `func` member function for this purpose:
  83. ```cpp
  84. entt::reflect<my_type>("reflected")
  85. .func<&my_type::static_function>("static")
  86. .func<&my_type::member_function>("member")
  87. .func<&free_function>("free");
  88. ```
  89. This function requires as an argument the name to give to the meta function
  90. once created. Users can then access meta functions at runtime by searching for
  91. them by name.
  92. * _Base classes_. A base class is such that the underlying type is actually
  93. derived from it. In this case, the reflection system tracks the relationship
  94. and allows for implicit casts at runtime when required.<br/>
  95. Use the `base` member function for this purpose:
  96. ```cpp
  97. entt::reflect<derived_type>("derived").base<base_type>();
  98. ```
  99. From now on, wherever a `base_type` is required, an instance of `derived_type`
  100. will also be accepted.
  101. * _Conversion functions_. Actual types can be converted, this is a fact. Just
  102. think of the relationship between a `double` and an `int` to see it. Similar
  103. to bases, conversion functions allow users to define conversions that will be
  104. implicitly performed by the reflection system when required.<br/>
  105. Use the `conv` member function for this purpose:
  106. ```cpp
  107. entt::reflect<double>().conv<int>();
  108. ```
  109. That's all, everything users need to create meta types and enjoy the reflection
  110. system. At first glance it may not seem that much, but users usually learn to
  111. appreciate it over time.<br/>
  112. Also, do not forget what these few lines hide under the hood: a built-in,
  113. non-intrusive and macro-free system for reflection in C++. Features that are
  114. definitely worth the price, at least for me.
  115. # Any as in any type
  116. The reflection system comes with its own meta any type. It may seem redundant
  117. since C++17 introduced `std::any`, but it is not.<br/>
  118. In fact, the _type_ returned by an `std::any` is a const reference to an
  119. `std::type_info`, an implementation defined class that's not something everyone
  120. wants to see in a software. Furthermore, the class `std::type_info` suffers from
  121. some design flaws and there is even no way to _convert_ an `std::type_info` into
  122. a meta type, thus linking the two worlds.
  123. A meta any object provides an API similar to that of its most famous counterpart
  124. and serves the same purpose of being an opaque container for any type of
  125. value.<br/>
  126. It minimizes the allocations required, which are almost absent thanks to _SBO_
  127. techniques. In fact, unless users deal with _fat types_ and create instances of
  128. them though the reflection system, allocations are at zero.
  129. A meta any object can be created by any other object or as an empty container
  130. to initialize later:
  131. ```cpp
  132. // a meta any object that contains an int
  133. entt::meta_any any{0};
  134. // an empty meta any object
  135. entt::meta_any empty{};
  136. ```
  137. It can be constructed or assigned by copy and move and it takes the burden of
  138. destroying the contained object when required.<br/>
  139. A meta any object has a `type` member function that returns the meta type of the
  140. contained value, if any. The member functions `can_cast` and `can_convert` are
  141. used to know if the underlying object has a given type as a base or if it can be
  142. converted implicitly to it. Similarly, `cast` and `convert` do what they promise
  143. and return the expected value.
  144. # Enjoy the runtime
  145. Once the web of reflected types has been constructed, it's a matter of using it
  146. at runtime where required.<br/>
  147. All this has the great merit that, unlike the vast majority of the things
  148. present in this library and closely linked to the compile-time, the reflection
  149. system stands in fact as a non-intrusive tool for the runtime.
  150. To search for a reflected type there are two options: by type or by name. In
  151. both cases, the search can be done by means of the `resolve` function:
  152. ```cpp
  153. // search for a reflected type by type
  154. auto by_type = entt::resolve<my_type>();
  155. // search for a reflected type by name
  156. auto by_name = entt::resolve("reflected_type");
  157. ```
  158. There exits also a third overload of the `resolve` function to use to iterate
  159. all the reflected types at once:
  160. ```cpp
  161. resolve([](auto type) {
  162. // ...
  163. });
  164. ```
  165. In all cases, the returned value is an instance of `meta_type`. This type of
  166. objects offer an API to know the _runtime name_ of the type, to iterate all the
  167. meta objects associated with them and even to build or destroy instances of the
  168. underlying type.<br/>
  169. Refer to the inline documentation for all the details.
  170. The meta objects that compose a meta type are accessed in the following ways:
  171. * _Meta constructors_. They are accessed by types of arguments:
  172. ```cpp
  173. auto ctor = entt::resolve<my_type>().ctor<int, char>();
  174. ```
  175. The returned type is `meta_ctor` and may be invalid if there is no constructor
  176. that accepts the supplied arguments or at least some types from which they are
  177. derived or to which they can be converted.<br/>
  178. A meta constructor offers an API to know the number of arguments, the expected
  179. meta types and to invoke it, therefore to construct a new instance of the
  180. underlying type.
  181. * _Meta destructor_. It's returned by a dedicated function:
  182. ```cpp
  183. auto dtor = entt::resolve<my_type>().dtor();
  184. ```
  185. The returned type is `meta_dtor` and may be invalid if there is no custom
  186. destructor set for the given meta type.<br/>
  187. All what a meta destructor has to offer is a way to invoke it on a given
  188. instance. Be aware that the result may not be what is expected.
  189. * _Meta data_. They are accessed by name:
  190. ```cpp
  191. auto data = entt::resolve<my_type>().data("member");
  192. ```
  193. The returned type is `meta_data` and may be invalid if there is no meta data
  194. object associated with the given name.<br/>
  195. A meta data object offers an API to query the underlying type (ie to know if
  196. it's a const or a static one), to get the meta type of the variable and to set
  197. or get the contained value.
  198. * _Meta functions_. They are accessed by name:
  199. ```cpp
  200. auto func = entt::resolve<my_type>().func("member");
  201. ```
  202. The returned type is `meta_func` and may be invalid if there is no meta
  203. function object associated with the given name.<br/>
  204. A meta function object offers an API to query the underlying type (ie to know
  205. if it's a const or a static function), to know the number of arguments, the
  206. meta return type and the meta types of the parameters. In addition, a meta
  207. function object can be used to invoke the underlying function and then get the
  208. return value in the form of meta any object.
  209. * _Meta bases_. They are accessed through the name of the base types:
  210. ```cpp
  211. auto base = entt::resolve<derived_type>().base("base");
  212. ```
  213. The returned type is `meta_base` and may be invalid if there is no meta base
  214. object associated with the given name.<br/>
  215. Meta bases aren't meant to be used directly, even though they are freely
  216. accessible. They expose only a few methods to use to know the meta type of the
  217. base class and to convert a raw pointer between types.
  218. * _Meta conversion functions_. They are accessed by type:
  219. ```cpp
  220. auto conv = entt::resolve<double>().conv<int>();
  221. ```
  222. The returned type is `meta_conv` and may be invalid if there is no meta
  223. conversion function associated with the given type.<br/>
  224. The meta conversion functions are as thin as the meta bases and with a very
  225. similar interface. The sole difference is that they return a newly created
  226. instance wrapped in a meta any object when they convert between different
  227. types.
  228. All the objects thus obtained as well as the meta types can be explicitly
  229. converted to a boolean value to check if they are valid:
  230. ```cpp
  231. auto func = entt::resolve<my_type>().func("member");
  232. if(func) {
  233. // ...
  234. }
  235. ```
  236. Furthermore, all meta objects with the exception of meta destructors can be
  237. iterated through an overload that accepts a callback through which to return
  238. them. As an example:
  239. ```cpp
  240. entt::resolve<my_type>().data([](auto data) {
  241. // ...
  242. });
  243. ```
  244. A meta type can also be used to `construct` or `destroy` actual instances of the
  245. underlying type.<br/>
  246. In particular, the `construct` member function accepts a variable number of
  247. arguments and searches for a match. It returns a `meta_any` object that may or
  248. may not be initialized, depending on whether a suitable constructor has been
  249. found or not. On the other side, the `destroy` member function accepts instances
  250. of `meta_any` as well as actual objects by reference and invokes the registered
  251. destructor if any or a default one.<br/>
  252. Be aware that the result of a call to `destroy` may not be what is expected.
  253. Meta types and meta objects in general contain much more than what is said: a
  254. plethora of functions in addition to those listed whose purposes and uses go
  255. unfortunately beyond the scope of this document.<br/>
  256. I invite anyone interested in the subject to look at the code, experiment and
  257. read the official documentation to get the best out of this powerful tool.
  258. # Named constants and enums
  259. A special mention should be made for constant values and enums. It wouldn't be
  260. necessary, but it will help distracted readers.
  261. As mentioned, the `data` member function can be used to reflect constants of any
  262. type among the other things.<br/>
  263. This allows users to create meta types for enums that will work exactly like any
  264. other meta type built from a class. Similarly, arithmetic types can be enriched
  265. with constants of special meaning where required.<br/>
  266. Personally, I find it very useful not to export what is the difference between
  267. enums and classes in C++ directly in the space of the reflected types.
  268. All the values thus exported will appear to users as if they were constant data
  269. members of the reflected types.
  270. Exporting constant values or elements from an enum is as simple as ever:
  271. ```cpp
  272. entt::reflect<my_enum>()
  273. .data<my_enum::a_value>("a_value")
  274. .data<my_enum::another_value>("another_value");
  275. entt::reflect<int>().data<2048>("max_int");
  276. ```
  277. It goes without saying that accessing them is trivial as well. It's a matter of
  278. doing the following, as with any other data member of a meta type:
  279. ```cpp
  280. auto value = entt::resolve<my_enum>().data("a_value").get({}).cast<my_enum>();
  281. auto max = entt::resolve<int>().data("max_int").get({}).cast<int>();
  282. ```
  283. As a side note, remember that all this happens behind the scenes without any
  284. allocation because of the small object optimization performed by the meta any
  285. class.
  286. # Properties and meta objects
  287. Sometimes (ie when it comes to creating an editor) it might be useful to be able
  288. to attach properties to the meta objects created. Fortunately, this is possible
  289. for most of them.<br/>
  290. To attach a property to a meta object, no matter what as long as it supports
  291. properties, it is sufficient to provide an object at the time of construction
  292. such that `std::get<0>` and `std::get<1>` are valid for it. In other terms, the
  293. properties are nothing more than key/value pairs users can put in an
  294. `std::pair`. As an example:
  295. ```cpp
  296. entt::reflect<my_type>("reflected", std::make_pair("tooltip"_hs, "message"));
  297. ```
  298. The meta objects that support properties offer then a couple of member functions
  299. named `prop` to iterate them at once and to search a specific property by key:
  300. ```cpp
  301. // iterate all the properties of a meta type
  302. entt::resolve<my_type>().prop([](auto prop) {
  303. // ...
  304. });
  305. // search for a given property by name
  306. auto prop = entt::resolve<my_type>().prop("tooltip"_hs);
  307. ```
  308. Meta properties are objects having a fairly poor interface, all in all. They
  309. only provide the `key` and the `value` member functions to be used to retrieve
  310. the key and the value contained in the form of meta any objects, respectively.
  311. # Unregister types
  312. A type registered with the reflection system can also be unregistered. This
  313. means unregistering all its data members, member functions, conversion functions
  314. and so on. However, the base classes won't be unregistered, since they don't
  315. necessarily depend on it. Similarly, implicitly generated types (as an example,
  316. the meta types implicitly generated for function parameters when needed) won't
  317. be unregistered.
  318. To unregister a type, users can use the `unregister` function from the global
  319. namespace:
  320. ```cpp
  321. entt::unregister<my_type>();
  322. ```
  323. This function returns a boolean value that is true if the type is actually
  324. registered with the reflection system, false otherwise.<br/>
  325. The type can be re-registered later with a completely different name and form.