EnTT: Crash Course: runtime reflection system

EnTT 3.16.0

Loading...
Searching...
No Matches
Crash Course: runtime reflection system

# Table of Contents

- Introduction
- Identifiers
- Reflection in a nutshell
  - Any to the rescue
  - Enjoy the runtime
    - Tell me your name
  - Container support
  - Pointer-like types
  - Template information
  - Automatic conversions
  - Implicitly generated default constructor
  - From void to any
  - Policies: the more, the less
  - Named constants and enums
  - User defined data
    - Traits
    - Custom data
  - Unregister types
  - Meta context

# Introduction

Reflection (or rather, its lack) is a trending topic in the C++ world and a tool that can unlock a lot of interesting features in the specific case of EnTT. I looked for a third-party library that met my needs on the subject, but I always came across some details that I did not like: macros, being intrusive, too many allocations, and so on.
I finally decided to write a built-in, non-intrusive and macro-free runtime reflection system for EnTT. Maybe I did not do better than others or maybe yes, time will tell me, but at least I can model this tool around the library to which it belongs and not the opposite.

# Identifiers

The meta system does not force users to rely on the tools provided by the library when it comes to working with identifiers. It does this by offering an API that works with integral values that may or may not be generated by means of a hashed string.
This means that users can assign any type of identifier to the meta objects, as long as they are numeric. It does not matter if they are generated at runtime, at compile-time or with custom functions.

That being said, some of the examples in the following sections are based on the hashed_string class as provided by this library. Therefore, where an integral identifier is provided, it is likely that a user defined literal is used as follows:

entt::meta_factory<my_type>{}.type("reflected_type"_hs);
entt::meta_factory
Meta factory to be used for reflection purposes.
Definition factory.hpp:158
entt::meta_factory::type
meta_factory type(const char *name) noexcept
Assigns a custom unique identifier to a meta type.
Definition factory.hpp:181

For what it is worth, this is completely equivalent to:

entt::meta_factory<my_type>{}.type(42u);

Obviously, human-readable identifiers are more convenient to use and highly recommended.

# Reflection in a nutshell

Reflection always starts from actual C++ types. Users cannot reflect imaginary types.
The meta_factory class is where it all starts:

entt::meta_factory<my_type> factory{};

The returned value is a factory object to use to continue building the meta type.

By default, a meta type is associated with the identifier returned by the runtime type identification system built-in in EnTT.
However, it is also possible to assign custom identifiers to meta types:

entt::meta_factory<my_type>{}.type("reflected_type"_hs);

Identifiers are used instead of the type to retrieve meta types at runtime, if necessary.
However, users can be interested in adding features to a reflected type so that the reflection system can use it correctly under the hood, while they do not want to also make the type searchable. In this case, it is sufficient not to invoke type.

A factory is such that all its member functions return the factory itself. It is generally used to create the following:

- Constructors. A constructor is assigned to a reflected type by specifying its list of arguments. Free functions are also accepted if the return type is the expected one. From a client perspective, nothing changes between a free function or an actual constructor:

  entt::meta_factory<my_type>{}.ctor<int, char>().ctor<&factory>();
  entt::meta_factory::ctor
  meta_factory ctor() noexcept
  Assigns a meta constructor to a meta type.
  Definition factory.hpp:263

  Meta default constructors are implicitly generated, if possible.

- Data members. Meta data members are actual data members of the underlying type but also static and global variables or constants of any kind. From the point of view of the client, all the variables associated with the reflected type appear as if they were part of the type itself:

  entt::meta_factory<my_type>{}
  .data<&my_type::static_variable>("static"_hs)
  .data<&my_type::data_member>("member"_hs)
  .data<&global_variable>("global"_hs);
  entt::meta_factory::data
  meta_factory data(const char *name) noexcept
  Assigns a meta data to a meta type.
  Definition factory.hpp:300

  The data function requires the identifier to use for the meta data member. This is then used for runtime access.
  Data members are also defined by means of a setter and getter pair. These are either free functions, class members or a mix of them. This approach is also convenient to create read-only properties from a non-const data member:

  entt::meta_factory<my_type>{}.data<nullptr, &my_type::data_member>("member"_hs);

- Member functions. Meta member functions are actual member functions of the underlying type but also plain free functions. From the point of view of the client, all the functions associated with the reflected type appear as if they were part of the type itself:

  entt::meta_factory<my_type>{}
  .func<&my_type::static_function>("static"_hs)
  .func<&my_type::member_function>("member"_hs)
  .func<&free_function>("free"_hs);
  entt::meta_factory::func
  meta_factory func(const char *name) noexcept
  Assigns a meta function to a meta type.
  Definition factory.hpp:438

  The func function requires the identifier to use for the meta data function. This is then used for runtime access.
  Overloading of meta functions is supported. Overloaded functions are resolved at runtime by the reflection system according to the types of the arguments.

- Base classes. A base class is such that the underlying type is actually derived from it:

  entt::meta_factory<derived_type>{}.base<base_type>();
  entt::meta_factory::base
  meta_factory base() noexcept
  Assigns a meta base to a meta type.
  Definition factory.hpp:205

  The reflection system tracks the relationship and allows for implicit casts at runtime when required. In other terms, wherever a base_type is required, an instance of derived_type is also accepted.

- Conversion functions. Conversion functions allow users to define conversions that are implicitly performed by the reflection system when required:

  entt::meta_factory<double>{}.conv<int>();
  entt::meta_factory::conv
  auto conv() noexcept
  Assigns a meta conversion function to a meta type.
  Definition factory.hpp:225

This is everything users need to create meta types. Refer to the inline documentation for further details.

## Any to the rescue

The reflection system offers a kind of extended version of the entt::any class (see the core module for more details).
The purpose is to add some feature on top of those already present, so as to integrate it with the meta type system without having to duplicate the code.

The API is very similar to that of the any type. The class meta_any wraps many of the feature to infer a meta node, before forwarding some or all of the arguments to the underlying storage.
Among the few relevant differences, meta_any adds support for containers and pointer-like types, while any does not.
Similar to any, this class is also used to create aliases for unmanaged objects either with forward_as_meta or using the std::in_place_type<T &> disambiguation tag, as well as from an existing object by means of the as_ref member function. Additionally, it can take ownership of pointers passed as arguments along with std::in_place.
Unlike any instead, meta_any treats an empty instance and one initialized with void differently:

entt::meta_any empty{};
entt::meta_any other{std::in_place_type<void>};
entt::meta_any
Opaque wrapper for values of any type.
Definition meta.hpp:159

While any considers both as empty, meta_any treats objects initialized with void as if they were valid ones. This allows differentiating between failed function calls and function calls that are successful but return nothing.

Finally, the member functions try_cast, cast and allow_cast are used to cast the underlying object to a given type (either a reference or a value type) or to convert a meta_any in such a way that a cast becomes viable for the resulting object.
There is in fact no any_cast equivalent for meta_any.

## Enjoy the runtime

Once the web of reflected types is constructed, it is a matter of using it at runtime where required.
There are a few options to search for a reflected type:

// direct access to a reflected type
auto by_type = entt::resolve<my_type>();
// look up a reflected type by identifier
auto by_id = entt::resolve("reflected_type"_hs);
// look up a reflected type by type info
auto by_type_id = entt::resolve(entt::type_id<my_type>());
entt::resolve
meta_type resolve() noexcept
Returns the meta type associated with a given type.
Definition resolve.hpp:32
entt::type_id
const type_info & type_id() noexcept
Returns the type info object associated to a given type.
Definition type_info.hpp:259

There exists also an overload of the resolve function to use to iterate all reflected types at once. It returns an iterable object to be used in a range-for loop:

for(auto &&[id, type]: entt::resolve()) {
// ...
}
entt::resolve
meta_type resolve(const meta_ctx &ctx) noexcept
Returns the meta type associated with a given type.
Definition resolve.hpp:21

In all cases, the returned value is an instance of meta_type (possibly with its id). These objects offer an API to know their runtime identifiers, to iterate all the meta objects associated with them and even to build instances of the underlying type.
Meta data members and functions are accessed by means of their identifiers:

- Meta data members:

  auto data = entt::resolve<my_type>().data("member"_hs);
  entt::meta_type::data
  meta_range< meta_data, typename decltype(internal::meta_type_descriptor::data)::const_iterator > data() const noexcept
  Returns a range to visit registered top-level meta data.
  Definition meta.hpp:1342

  The returned type is meta_data and may be invalid if there is no meta data object associated with the given identifier.
  A meta data object offers an API to query the underlying type (for example, to know if it is a const or a static one), to get the meta type of the variable and to set or get the contained value.

- Meta function members:

  auto func = entt::resolve<my_type>().func("member"_hs);
  entt::meta_type::func
  meta_range< meta_func, typename decltype(internal::meta_type_descriptor::func)::const_iterator > func() const noexcept
  Returns a range to visit registered top-level functions.
  Definition meta.hpp:1362

  The returned type is meta_func and may be invalid if there is no meta function object associated with the given identifier.
  A meta function object offers an API to query the underlying type (for example, to know if it is a const or a static function), to know the number of arguments, the meta return type and the meta types of the parameters. In addition, a meta function object is used to invoke the underlying function and then get the return value in the form of a meta_any object.

Both functions search for the elements throughout the meta type hierarchy. However, they offer the option of passing a second boolean argument to stop the search at the top-level meta type.
All the meta objects thus obtained as well as the meta types explicitly convert to a boolean value to check for validity:

if(auto func = entt::resolve<my_type>().func("member"_hs); func) {
// ...
}

Furthermore, all of them (and a few more, like meta basis) are returned by a bunch of overloads that provide the caller with iterable ranges of top-level elements. As an example:

for(auto &&[id, type]: entt::resolve<my_type>().base()) {
// ...
}

Meta types are also used to construct actual instances of the underlying type.
In particular, the construct member function accepts a variable number of arguments and searches for a match. It then returns a meta_any object that may or may not be initialized, depending on whether a suitable constructor was found or not.
Conversion functions are not accessible instead. They are used internally by meta_any and the meta objects when needed.

Meta types and meta objects in general contain much more than what was said. Refer to the inline documentation for further details.

### Tell me your name

For meta types, data and functions, users can also provide custom names:

entt::meta_factory<my_type>{}
.type("type"_hs, "my_type")
.data<&variable>("data"_hs, "variable")
.func<&function>("func"_hs, "function");

The label provided should be a string literal. The library does not make copies. It is up to the user to guarantee the lifetime of the name itself.
String identifiers are returned from the meta objects via the name function:

const char *name = entt::resolve<my_type>().name();
entt::meta_type::name
const char * name() const noexcept
Returns the name assigned to a type, if any.
Definition meta.hpp:1161

Since most of the time there is no need to differentiate the name from the numeric identifier associated with a meta object, EnTT also offers a more compact version of these functions:

entt::meta_factory<my_type>{}
.type("my_type")
.data<&variable>("variable")
.func<&function>("function");

Again, the name provided should be a string literal. The string is then used to generate a numeric identifier with the hashed_string class.
Despite support for names, there are no string-based lookup functions available. That is, types (resolve) as well as data members (data) and function members (func) are only searchable by numeric identifiers.

## Container support

The runtime reflection system also supports containers of all types.
Moreover, containers does not necessarily mean those offered by the C++ standard library. In fact, user defined data structures can also work with the meta system in many cases.

To make a container be recognized as such by the meta system, users are required to provide specializations for either the meta_sequence_container_traits class or the meta_associative_container_traits class, according to the actual type of the container.
EnTT already exports the specializations for some common classes. In particular:

- std::vector, std::array, std::deque and std::list (but not std::forward_list) are supported as sequence containers.
- std::map, std::set and their unordered counterparts are supported as associative containers.

It is important to include the header file container.hpp to make these specializations available to the compiler when needed.
The same file also contains many examples for the users that are interested in making their own containers available to the meta system.

When a specialization of the meta_sequence_container_traits class exists, the meta system treats the wrapped type as a sequence container. In a similar way, a type is treated as an associative container if a specialization of the meta_associative_container_traits class is found for it.
Proxy objects are returned by dedicated members of the meta_any class. The following is a deliberately verbose example of how users can access a proxy object for a sequence container:

std::vector<int> vec{1, 2, 3};
entt::meta_any any = entt::forward_as_meta(vec);
if(any.type().is_sequence_container()) {
if(auto view = any.as_sequence_container(); view) {
// ...
}
}
entt::basic_any::type
const type_info & type() const noexcept
Returns the object type info if any, type_id<void>() otherwise.
Definition any.hpp:358
entt::forward_as_meta
meta_any forward_as_meta(const meta_ctx &ctx, Type &&value)
Forwards its argument and avoids copies for lvalue references.
Definition meta.hpp:647

The method to use to get a proxy object for associative containers is as_associative_container instead.
It is not necessary to perform a double check actually. Instead, it is enough to query the meta type or verify that the proxy object is valid. In fact, proxies are contextually convertible to bool to check for validity. For example, invalid proxies are returned when the wrapped object is not a container.
In all cases, users are not expected to reflect containers explicitly. It is sufficient to assign a container for which a specialization of the traits classes exists to a meta_any object to be able to get its proxy object.

The interface of the meta_sequence_container proxy object is the same for all types of sequence containers, although the available features differ from case to case. In particular:

- The value_type member function returns the meta type of the elements.
- The size member function returns the number of elements in the container as an unsigned integer value.
- The resize member function allows resizing the wrapped container and returns true in case of success.
  For example, it is not possible to resize fixed size containers.
- The clear member function allows clearing the wrapped container and returns true in case of success.
  For example, it is not possible to clear fixed size containers.
- The reserve member function allows increasing the capacity of the wrapped container and returns true in case of success.
  For example, it is not possible to increase capacity of fixed size containers.

- The begin and end member functions return opaque iterators that is used to iterate the container directly:

  for(entt::meta_any element: view) {
  // ...
  }

  In all cases, given an underlying container of type C, the returned element contains an object of type C::value_type which therefore depends on the actual container.
  All meta iterators are input iterators and do not offer an indirection operator on purpose.

- The insert member function is used to add elements to the container. It accepts a meta iterator and the element to insert:

  auto last = view.end();
  // appends an integer to the container
  view.insert(last, 42);

  This function returns a meta iterator pointing to the inserted element and a boolean value to indicate whether the operation was successful or not. A call to insert may silently fail in case of fixed size containers or whether the arguments are not at least convertible to the required types.
  Since meta iterators are contextually convertible to bool, users can rely on them to know if the operation failed on the actual container or upstream, for example due to an argument conversion problem.

- The erase member function is used to remove elements from the container. It accepts a meta iterator to the element to remove:

  auto first = view.begin();
  // removes the first element from the container
  view.erase(first);

  This function returns a meta iterator following the last removed element and a boolean value to indicate whether the operation was successful or not. A call to erase may silently fail in case of fixed size containers.

- The operator[] is used to access container elements. It accepts a single argument, the position of the element to return:

  for(std::size_t pos{}, last = view.size(); pos < last; ++pos) {
  entt::meta_any value = view[pos];
  // ...
  }

  The function returns instances of meta_any that directly refer to the actual elements. Modifying the returned object directly modifies the element inside the container.
  Depending on the underlying sequence container, this operation may not be as efficient. For example, in the case of an std::list, a positional access translates to a linear visit of the list itself (probably not what the user expects).

Similarly, also the interface of the meta_associative_container proxy object is the same for all types of associative containers. However, there are some differences in behavior in the case of key-only containers. In particular:

- The key_only member function returns true if the wrapped container is a key-only one.
- The key_type member function returns the meta type of the keys.
- The mapped_type member function returns an invalid meta type for key-only containers and the meta type of the mapped values for all other types of containers.
- The value_type member function returns the meta type of the elements.
  For example, it returns the meta type of int for std::set<int> while it returns the meta type of std::pair<const int, char> for std::map<int, char>.
- The size member function returns the number of elements in the container as an unsigned integer value.
- The clear member function allows clearing the wrapped container and returns true in case of success.
- The reserve member function allows increasing the capacity of the wrapped container and returns true in case of success.
  For example, it is not possible to increase capacity of standard maps.

- The begin and end member functions return opaque iterators that are used to iterate the container directly:

  for(std::pair<entt::meta_any, entt::meta_any> element: view) {
  // ...
  }

  In all cases, given an underlying container of type C, the returned element is a key-value pair where the key has type C::key_type and the value has type C::mapped_type. Since key-only containers do not have a mapped type, their value is nothing more than an invalid meta_any object.
  All meta iterators are input iterators and do not offer an indirection operator on purpose.

  While the accessed key is usually constant in the associative containers and is therefore returned by copy, the value (if any) is wrapped by an instance of meta_any that directly refers to the actual element. Modifying it directly modifies the element inside the container.

- The insert member function is used to add elements to a container. It gets two arguments, the key and the value to insert:

  auto last = view.end();
  // appends an integer to the container
  view.insert(last.handle(), 42, 'c');

  This function returns a boolean value to indicate whether the operation was successful or not. A call to insert may fail when the arguments are not at least convertible to the required types.

- The erase member function is used to remove elements from a container. It gets a single argument, the key to remove:

  view.erase(42);

  This function returns a boolean value to indicate whether the operation was successful or not. A call to erase may fail when the argument is not at least convertible to the required type.

- The operator[] is used to access elements in a container. It gets a single argument, the key of the element to return:

  entt::meta_any value = view[42];

  The function returns instances of meta_any that directly refer to the actual elements. Modifying the returned object directly modifies the element inside the container.

Container support is minimal but likely sufficient to satisfy all needs.

## Pointer-like types

As with containers, it is also possible to tell to the meta system which types are pointers. This makes it possible to dereference instances of meta_any, thus obtaining light references to pointed objects that are also correctly associated with their meta types.
To make the meta system recognize a type as pointer-like, users can specialize the is_meta_pointer_like class. EnTT already exports the specializations for some common classes. In particular:

- All types of raw pointers.
- std::unique_ptr and std::shared_ptr.
- All classes that export a type member called is_meta_pointer_like:
  struct smart_pointer {
  using is_meta_pointer_like = void;
  // ...
  };
  The actual type is irrelevant and will not be used in any way.

It is important to include the header file pointer.hpp to make these specializations available to the compiler when needed.
The same file also contains many examples for the users that are interested in making their own pointer-like types available to the meta system.

When a type is recognized as a pointer-like one by the meta system, it is possible to dereference the instances of meta_any that contain these objects. The following is a deliberately verbose example to show how to use this feature:

int value = 42;
// meta type equivalent to that of int *
entt::meta_any any{&value};
if(any.type().is_pointer_like()) {
// meta type equivalent to that of int
if(entt::meta_any ref = *any; ref) {
// ...
}
}

It is not necessary to perform a double check. Instead, it is enough to query the meta type or verify that the returned object is valid. For example, invalid instances are returned when the wrapped object is not a pointer-like type.
Dereferencing a pointer-like object returns an instance of meta_any which refers to the pointed object. Modifying it means modifying the pointed object directly (unless the returned element is const).

In general, dereferencing a pointer-like type boils down to a *ptr. However, EnTT also supports classes that do not offer an operator*. In particular:

- It is possible to exploit a solution based on ADL lookup by implementing a function (also a template one) named dereference_meta_pointer_like:

  template<typename Type>
  Type & dereference_meta_pointer_like(const custom_pointer_type<Type> &ptr) {
  return ptr.deref();
  }

- When not in control of the type's namespace, it is possible to inject into the entt namespace a specialization of the adl_meta_pointer_like class template to bypass the adl lookup as a whole:

  template<typename Type>
  struct entt::adl_meta_pointer_like<custom_pointer_type<Type>> {
  static decltype(auto) dereference(const custom_pointer_type<Type> &ptr) {
  return ptr.deref();
  }
  };
  entt::adl_meta_pointer_like
  Fake ADL based lookup function for meta pointer-like types.
  Definition adl_pointer.hpp:22
  entt::adl_meta_pointer_like::dereference
  static decltype(auto) dereference(const Type &value)
  Uses the default ADL based lookup method to resolve the call.
  Definition adl_pointer.hpp:28

In all other cases and when dereferencing a pointer works as expected regardless of the pointed type, no user intervention is required.

## Template information

Meta types also provide a minimal set of information about the nature of the original type in case it is a class template.
By default, this works out of the box and requires no user action. However, it is important to include the header file template.hpp to make this information available to the compiler when needed.

Meta template information is easily found:

// this method returns true if the type is recognized as a class template specialization
if(auto type = entt::resolve<std::shared_ptr<my_type>>(); type.is_template_specialization()) {
// meta type of the class template conveniently wrapped by entt::meta_class_template_tag
auto class_type = type.template_type();
// number of template arguments
std::size_t arity = type.template_arity();
// meta type of the i-th argument
auto arg_type = type.template_arg(0u);
}

Typically, when template information for a type is required, what the library provides is sufficient. However, there are some cases where a user may want more details or a different set of information.
Consider the case of a class template that is meant to wrap function types:

template<typename>
struct function_type;
template<typename Ret, typename... Args>
struct function_type<Ret(Args...)> {};

In this case, rather than the function type, it might be useful to provide the return type and unpacked arguments as if they were different template parameters for the original class template.
To achieve this, users must enter the library internals and provide their own specialization for the class template entt::meta_template_traits, such as:

template<typename Ret, typename... Args>
struct entt::meta_template_traits<function_type<Ret(Args...)>> {
using class_type = meta_class_template_tag<function_type>;
using args_type = type_list<Ret, Args...>;
};
entt::meta_template_traits
Traits class template to be specialized to enable support for meta template information.
Definition type_traits.hpp:14

The reflection system does not verify the accuracy of the information nor infer a correspondence between real types and meta types.
Therefore, the specialization is used as is and the information it contains is associated with the appropriate type when required.

## Automatic conversions

In C++, there are a number of conversions allowed between arithmetic types that make it convenient to work with this kind of data.
If this were to be translated into explicit registrations with the reflection system, it would result in a long series of instructions such as the following:

entt::meta_factory<int>{}
.conv<bool>()
.conv<char>()
// ...
.conv<double>();

Repeated for each type eligible to undergo this type of conversions. This is both error-prone and repetitive.
Similarly, the language allows users to silently convert unscoped enums to their underlying types and offers what it takes to do the same for scoped enums. It would result in the following if it were to be done explicitly:

entt::meta_factory<my_enum>{}
.conv<std::underlying_type_t<my_enum>>();

Fortunately, all of this can also be avoided. EnTT offers implicit support for these types of conversions:

entt::meta_any any{42};
any.allow_cast<double>();
double value = any.cast<double>();

With no need for registration, the conversion takes place automatically under the hood. The same goes for a call to allow_cast involving a meta type:

entt::meta_type type = entt::resolve<int>();
entt::meta_any any{my_enum::a_value};
any.allow_cast(type);
int value = any.cast<int>();
entt::meta_type
Opaque wrapper for types.
Definition meta.hpp:1059

This makes working with arithmetic types and scoped or unscoped enums as easy as it is in C++.
It is still possible to set up conversion functions manually, and these are always preferred over the automatic ones.

## Implicitly generated default constructor

Creating objects of default constructible types through the reflection system while not having to explicitly register the meta type or its default constructor is also possible.
For example, in the case of primitive types like int or char, but not just them.

For default constructible types only, default constructors are automatically defined and associated with their meta types, whether they are explicitly or implicitly generated.
Therefore, this is all needed to construct an integer from its meta type:

entt::resolve<int>().construct();
entt::meta_type::construct
meta_any construct(meta_any *const args, const size_type sz) const
Creates an instance of the underlying type, if possible.
Definition meta.hpp:1384

Where the meta type is, for example, the one returned from a meta container, useful for building keys without knowing or having to register the actual types.

In all cases, when users register default constructors, they are preferred both during searches and when the construct member function is invoked.

## From void to any

Sometimes all a user has is an opaque pointer to an object of a known meta type. It would be handy in this case to be able to construct a meta_any element from it.
For this purpose, the meta_type class offers a from_void member function designed to convert an opaque pointer into a meta_any:

entt::meta_any any = entt::resolve(id).from_void(element);
entt::meta_type::from_void
meta_any from_void(void *elem, bool transfer_ownership=false) const
Wraps an opaque element of the underlying type.
Definition meta.hpp:1416

Unfortunately, it is not possible to do a check on the actual type. Therefore, this call can be considered as a static cast with all its problems.
On the other hand, the ability to construct a meta_any from an opaque pointer opens the door to some pretty interesting uses that are worth exploring.

## Policies: the more, the less

Policies are a kind of compile-time directives that can be used when registering reflection information.
Their purpose is to require slightly different behavior than the default in some specific cases. For example, when reading a given data member, its value is returned wrapped in a meta_any object which, by default, makes a copy of it. For large objects or if the caller wants to access the original instance, this behavior is not desirable. Policies are there to offer a solution to this and other problems.

There are a few alternatives available at the moment:

- The as-value policy, associated with the type entt::as_value_t.
  This is the default policy. In general, it should never be used explicitly, since it is implicitly selected if no other policy is specified.
  In this case, the return values of the functions as well as the properties exposed as data members are always returned by copy in a dedicated wrapper and therefore associated with their original meta types.

- The as-void policy, associated with the type entt::as_void_t.
  Its purpose is to discard the return value of a meta object, whatever it is, thus making it appear as if its type were void:

  entt::meta_factory<my_type>{}.func<&my_type::member_function, entt::as_void_t>("member"_hs);
  entt::as_void_t
  Empty class type used to request the as void policy.
  Definition policy.hpp:25

  If the use with functions is obvious, perhaps less so is use with constructors and data members. In the first case, the returned wrapper is always empty even though the constructor is still invoked. In the second case, the property is not accessible for reading instead.

- The as-ref and as-cref policies, associated with the types entt::as_ref_t and entt::as_cref_t.
  They allow to build wrappers that act as references to unmanaged objects. Accessing the object contained in the wrapper for which the reference was requested makes it possible to directly access the instance used to initialize the wrapper itself:

  entt::meta_factory<my_type>{}.data<&my_type::data_member, entt::as_ref_t>("member"_hs);
  entt::as_ref_t
  Empty class type used to request the as ref policy.
  Definition policy.hpp:33

  These policies work with constructors (for example, when objects are taken from an external container rather than created on demand), data members and functions in general.
  If on the one hand as_cref_t always forces the return type to be const, as_ref_t adapts to the constness of the passed object and to that of the return type if any.

- The as-is policy, associated with the type entt::as_is_t.
  Useful for decoupling meta type creation code from calling code while still preserving the behavior of data members and member functions as defined:

  entt::meta_factory<my_type>{}.func<&my_type::any_member, entt::as_is_t>("member"_hs);
  entt::as_is_t
  Empty class type used to request the as auto policy.
  Definition policy.hpp:49

  For data members or member functions that return a reference type, the value is returned by reference with the same constness. In all other cases, the value is returned by copy.

Some uses are rather trivial, but it is useful to note that there are some less obvious corner cases that can in turn be solved with the use of policies.

## Named constants and enums

As mentioned, the data member function is used to reflect constants of any type.
This allows users to create meta types for enums that work exactly like any other meta type built from a class. Similarly, arithmetic types are enriched with constants of special meaning where required.
All values thus exported appear to users as if they were constant data members of the reflected types. This avoids the need to export what is the difference between enums and classes in C++ directly in the space of the reflected types.

Exposing constant values or elements from an enum is quite simple:

entt::meta_factory<my_enum>{}
.data<my_enum::a_value>("a_value"_hs)
.data<my_enum::another_value>("another_value"_hs);
entt::meta_factory<int>{}.data<2048>("max_int"_hs);

Accessing them is trivial as well. It is a matter of doing the following, as with any other data member of a meta type:

auto value = entt::resolve<my_enum>().data("a_value"_hs).get({}).cast<my_enum>();
auto max = entt::resolve<int>().data("max_int"_hs).get({}).cast<int>();

All this happens behind the scenes without any allocation because of the small object optimization performed by the meta_any class.

## User defined data

Sometimes (for example, when it comes to creating an editor) it might be useful to attach traits or arbitrary custom data to the meta objects created.

The main difference between them is that:

- Traits are simple user-defined flags with much higher access performance. The library reserves up to 16 bits for traits, that is 16 flags for a bitmask or 2^16 values otherwise.
- Custom data are stored in a generic quick access area reserved for the user and which the library will never use under any circumstances.

In all cases, this support is currently available only for meta types, meta data and meta functions.

### Traits

User-defined traits are set via a meta factory:

entt::meta_factory<my_type>{}.traits(my_traits::required | my_traits::hidden);
entt::meta_factory::traits
meta_factory traits(const Value value, const bool unset=false)
Sets traits on the last created meta object.
Definition factory.hpp:485

In the example above, EnTT bitmask enum support is used, but any integral value is fine, as long as it does not exceed 16 bits.
Traits can be assigned at different times. Subsequent calls to the traits function do not reset previously set values. However, users must reset the factory to the meta object of interest:

entt::meta_factory<my_type>{}
.data<&my_type::data_member, entt::as_ref_t>("member"_hs)
.traits(my_traits::internal);

Once created, all meta objects offer a member function named traits to get the currently set value:

auto value = entt::resolve<my_type>().traits<my_traits>();
entt::meta_type::traits
Type traits() const noexcept
Returns all meta traits for a given meta object.
Definition meta.hpp:1506

Note that the type is erased upon registration and must therefore be repeated when traits are extracted, so as to allow the library to reconstruct them correctly.

### Custom data

Custom arbitrary data are set via a meta factory:

entt::meta_factory<my_type>{}.custom<type_data>("name");
entt::meta_factory::custom
meta_factory custom(Args &&...args)
Sets user defined data that will never be used by the library.
Definition factory.hpp:499

The way to do this is by specifying the data type to the custom function and passing the necessary arguments to construct it correctly.
It is not possible to assign custom data at different times. Therefore, multiple calls to the custom function overwrite previous values. However, this value can be read from meta objects and used to update existing data with a factory, effectively updating them as needed.
Likewise, users can also set custom data on meta objects later if needed, as long as the factory is reset to the meta object of interest:

entt::meta_factory<my_type>{}
.func<&my_type::member_function>("member"_hs)
.custom<function_data>("tooltip");

Once created, all meta objects offer a member function named custom to get the currently set value as a reference or as a pointer to an element:

const type_data &value = entt::resolve<my_type>().custom();
entt::meta_type::custom
meta_custom custom() const noexcept
Returns user defined data for a given meta object.
Definition meta.hpp:1511

Note that the returned object performs an extra check in debug before converting to the requested type, so as to avoid subtle bugs.
Only in the case of conversion to a pointer is this check safe and such that a null pointer is returned to inform the user of the failed attempt.

## Unregister types

A type registered with the reflection system can also be unregistered. This means unregistering all its data members, member functions, conversion functions and so on. However, base classes are not unregistered as well, since they do not necessarily depend on it.
Roughly speaking, unregistering a type means disconnecting all associated meta objects from it and making its identifier no longer available:

entt::meta_reset<my_type>();
entt::meta_reset
void meta_reset() noexcept
Resets a type and all its parts.
Definition factory.hpp:565

It is also possible to reset types by their unique identifiers:

entt::meta_reset("my_type"_hs);

Finally, there exists a non-template overload of the meta_reset function that does not accept arguments and resets all meta types at once:

entt::meta_reset();

A type can be re-registered later with a completely different name and form.

## Meta context

All meta types and their parts are created at runtime and stored in a default context. This is obtained via a service locator as:

auto &&context = entt::locator<entt::meta_context>::value_or();
entt::locator::value_or
static Service & value_or(Args &&...args)
Returns a service if available or sets it from a fallback type.
Definition locator.hpp:88

By itself, a context is an opaque object that the user can do little with. However, users can replace an existing context with another at any time:

entt::meta_context other{};
auto &&context = entt::locator<entt::meta_context>::value_or();
std::swap(context, other);

This is useful for testing purposes or to define multiple context objects with different meta types to use as appropriate.

If replacing the default context is not enough, EnTT also offers the ability to use multiple and externally managed contexts with the runtime reflection system.
For example, to create new meta types within a context other than the default one, simply pass it as an argument to the meta_factory constructor:

entt::meta_ctx context{};
entt::meta_factory<my_type>{context}.type("reflected_type"_hs);
entt::meta_ctx
Opaque meta context type.
Definition context.hpp:34

By doing so, the new meta type is not available in the default context but is usable by passing around the new context when needed, such as when creating a new meta_any object:

entt::meta_any any{context, std::in_place_type<my_type>};

Similarly, to search for meta types in a context other than the default one, it is necessary to pass it to the resolve function:

entt::meta_type type = entt::resolve(context, "reflected_type"_hs)

More generally, when using externally managed contexts, it is always required to provide the system with the context to use, at least at the entry point.
For example, once the meta_type instant is obtained, it is no longer necessary to pass the context around as the meta type takes the information with it and eventually propagates it to all its parts.
On the other hand, it is necessary to instruct the library on where meta types are to be fetched when meta_anys and meta_handles are constructed, a factory created or a meta type resolved.