# Crash Course: entity-component system # Table of Contents * [Introduction](#introduction) * [Design decisions](#design-decisions) * [Type-less and bitset-free](#type-less-and-bitset-free) * [Build your own](#build-your-own) * [Pay per use](#pay-per-use) * [All or nothing](#all-or-nothing) * [Vademecum](#vademecum) * [Pools](#pools) * [The Registry, the Entity and the Component](#the-registry-the-entity-and-the-component) * [Observe changes](#observe-changes) * [They call me Reactive System](#they-call-me-reactive-system) * [Sorting: is it possible?](#sorting-is-it-possible) * [Helpers](#helpers) * [Null entity](#null-entity) * [Tombstone](#tombstone) * [To entity](#to-entity) * [Dependencies](#dependencies) * [Invoke](#invoke) * [Handle](#handle) * [Organizer](#organizer) * [Context variables](#context-variables) * [Aliased properties](#aliased-properties) * [Component traits](#component-traits) * [Pointer stability](#pointer-stability) * [In-place delete](#in-place-delete) * [Hierarchies and the like](#hierarchies-and-the-like) * [Meet the runtime](#meet-the-runtime) * [A base class to rule them all](#a-base-class-to-rule-them-all) * [Beam me up, registry](#beam-me-up-registry) * [Snapshot: complete vs continuous](#snapshot-complete-vs-continuous) * [Snapshot loader](#snapshot-loader) * [Continuous loader](#continuous-loader) * [Archives](#archives) * [One example to rule them all](#one-example-to-rule-them-all) * [Views and Groups](#views-and-groups) * [Views](#views) * [Iteration order](#iteration-order) * [View pack](#view-pack) * [Runtime views](#runtime-views) * [Groups](#groups) * [Full-owning groups](#full-owning-groups) * [Partial-owning groups](#partial-owning-groups) * [Non-owning groups](#non-owning-groups) * [Nested groups](#nested-groups) * [Types: const, non-const and all in between](#types-const-non-const-and-all-in-between) * [Give me everything](#give-me-everything) * [What is allowed and what is not](#what-is-allowed-and-what-is-not) * [More performance, more constraints](#more-performance-more-constraints) * [Empty type optimization](#empty-type-optimization) * [Multithreading](#multithreading) * [Iterators](#iterators) * [Const registry](#const-registry) * [Beyond this document](#beyond-this-document) # Introduction `EnTT` is a header-only, tiny and easy to use entity-component system (and much more) written in modern C++.
The entity-component-system (also known as _ECS_) is an architectural pattern used mostly in game development. # Design decisions ## Type-less and bitset-free `EnTT` offers a sparse set based model that doesn't require users to specify the set of components neither at compile-time nor at runtime.
This is why users can instantiate the core class simply like: ```cpp entt::registry registry; ``` In place of its more annoying and error-prone counterpart: ```cpp entt::registry registry; ``` Furthermore, it isn't necessary to announce the existence of a component type. When the time comes, just use it and that's all. ## Build your own `EnTT` is designed as a container that can be used at any time, just like a vector or any other container. It doesn't attempt in any way to take over on the user codebase, nor to control its main loop or process scheduling.
Unlike other more or less well known models, it also makes use of independent pools that can be extended via _static mixins_. The built-in signal support is an example of this flexible model: defined as a mixin, it's easily disabled if not needed. Similarly, the storage class has a specialization that shows how everything is customizable down to the smallest detail. ## Pay per use `EnTT` is entirely designed around the principle that users have to pay only for what they want. When it comes to using an entity-component system, the tradeoff is usually between performance and memory usage. The faster it is, the more memory it uses. Even worse, some approaches tend to heavily affect other functionalities like the construction and destruction of components to favor iterations, even when it isn't strictly required. In fact, slightly worse performance along non-critical paths are the right price to pay to reduce memory usage and have overall better performance.
`EnTT` follows a completely different approach. It gets the best out from the basic data structures and gives users the possibility to pay more for higher performance where needed. So far, this choice has proven to be a good one and I really hope it can be for many others besides me. ## All or nothing `EnTT` is such that a `T**` pointer (or whatever a custom pool returns) is always available to directly access all the instances of a given component type `T`.
I cannot say whether it will be useful or not to the reader, but it's worth to mention it since it's one of the corner stones of this library. Many of the tools described below give the possibility to get this information and have been designed around this need.
The rest is experimentation and the desire to invent something new, hoping to have succeeded. # Vademecum The registry to store, the views and the groups to iterate. That's all. The `entt::entity` type implements the concept of _entity identifier_. An entity (the _E_ of an _ECS_) is an opaque element to use as-is. Inspecting it isn't recommended since its format can change in future.
Components (the _C_ of an _ECS_) are of any type, without any constraints, not even that of being movable. No need to register them nor their types.
Systems (the _S_ of an _ECS_) can be plain functions, functors, lambdas and so on. It's not required to announce them in any case and have no requirements. The next sections go into detail on how to use the entity-component system part of the `EnTT` library.
The project is composed of many other classes in addition to those described below. For more details, please refer to the inline documentation. # Pools Pools of components are a sort of _specialized version_ of a sparse set. Each pool contains all the instances of a single component type and all the entities to which it's assigned.
Sparse arrays are _paged_ to avoid wasting memory. Packed arrays of components are also paged to have pointer stability upon additions. Packed arrays of entities are not instead.
All pools rearranges their items in order to keep the internal arrays tightly packed and maximize performance, unless pointer stability is enabled. # The Registry, the Entity and the Component A registry stores and manages entities (or better, identifiers) and pools.
The class template `basic_registry` lets users decide what's the preferred type to represent an entity. Because `std::uint32_t` is large enough for almost all the cases, there also exists the enum class `entt::entity` that _wraps_ it and the alias `entt::registry` for `entt::basic_registry`. Entities are represented by _entity identifiers_. An entity identifier contains information about the entity itself and its version.
User defined identifiers are allowed as enum classes and class types that define an `entity_type` member of type `std::uint32_t` or `std::uint64_t`. A registry is used both to construct and to destroy entities: ```cpp // constructs a naked entity with no components and returns its identifier auto entity = registry.create(); // destroys an entity and all its components registry.destroy(entity); ``` The `create` member function also accepts a hint and has an overload that gets two iterators and can be used to generate multiple entities at once efficiently. Similarly, the `destroy` member function also works with a range of entities: ```cpp // destroys all the entities in a range auto view = registry.view(); registry.destroy(view.begin(), view.end()); ``` In addition to offering an overload to force the version upon destruction. Note that this function removes all components from an entity before releasing its identifier. There also exists a _lighter_ alternative that only releases the elements without poking in any pool, for use with orphaned entities: ```cpp // releases an orphaned identifier registry.release(entity); ``` As with the `destroy` function, also in this case entity ranges are supported and it's possible to force the version during release. In both cases, when an identifier is released, the registry can freely reuse it internally. In particular, the version of an entity is increased (unless the overload that forces a version is used instead of the default one).
Users can probe an identifier to know the information it carries: ```cpp // returns true if the entity is still valid, false otherwise bool b = registry.valid(entity); // gets the version contained in the entity identifier auto version = registry.version(entity); // gets the actual version for the given entity auto curr = registry.current(entity); ``` Components can be assigned to or removed from entities at any time. As for the entities, the registry offers a set of functions to use to work with components. The `emplace` member function template creates, initializes and assigns to an entity the given component. It accepts a variable number of arguments to use to construct the component itself if present: ```cpp registry.emplace(entity, 0., 0.); // ... auto &vel = registry.emplace(entity); vel.dx = 0.; vel.dy = 0.; ``` The default storage _detects_ aggregate types internally and exploits aggregate initialization when possible.
Therefore, it's not strictly necessary to define a constructor for each type, in accordance with the rules of the language. On the other hand, `insert` works with _ranges_ and can be used to: * Assign the same component to all entities at once when a type is specified as a template parameter or an instance is passed as an argument: ```cpp // default initialized type assigned by copy to all entities registry.insert(first, last); // user-defined instance assigned by copy to all entities registry.insert(from, to, position{0., 0.}); ``` * Assign a set of components to the entities when a range is provided (the length of the range of components must be the same of that of entities): ```cpp // first and last specify the range of entities, instances points to the first element of the range of components registry.insert(first, last, instances); ``` If an entity already has the given component, the `replace` and `patch` member function templates can be used to update it: ```cpp // replaces the component in-place registry.patch(entity, [](auto &pos) { pos.x = pos.y = 0.; }); // constructs a new instance from a list of arguments and replaces the component registry.replace(entity, 0., 0.); ``` When it's unknown whether an entity already owns an instance of a component, `emplace_or_replace` is the function to use instead: ```cpp registry.emplace_or_replace(entity, 0., 0.); ``` This is a slightly faster alternative for the following snippet: ```cpp if(registry.all_of(entity)) { registry.replace(entity, 0., 0.); } else { registry.emplace(entity, 0., 0.); } ``` The `all_of` and `any_of` member functions may also be useful if in doubt about whether or not an entity has all the components in a set or any of them: ```cpp // true if entity has all the given components bool all = registry.all_of(entity); // true if entity has at least one of the given components bool any = registry.any_of(entity); ``` If the goal is to delete a component from an entity that owns it, the `erase` member function template is the way to go: ```cpp registry.erase(entity); ``` When in doubt whether the entity owns the component, use the `remove` member function instead. It behaves similarly to `erase` but it erases the component if and only if it exists, otherwise it returns safely to the caller: ```cpp registry.remove(entity); ``` The `clear` member function works similarly and can be used to either: * Erases all instances of the given components from the entities that own them: ```cpp registry.clear(); ``` * Or destroy all entities in a registry at once: ```cpp registry.clear(); ``` Finally, references to components can be retrieved simply as: ```cpp const auto &cregistry = registry; // const and non-const reference const auto &crenderable = cregistry.get(entity); auto &renderable = registry.get(entity); // const and non-const references const auto [cpos, cvel] = cregistry.get(entity); auto [pos, vel] = registry.get(entity); ``` The `get` member function template gives direct access to the component of an entity stored in the underlying data structures of the registry. There exists also an alternative member function named `try_get` that returns a pointer to the component owned by an entity if any, a null pointer otherwise. ## Observe changes By default, each storage comes with a mixin that adds signal support to it.
This allows for fancy things like dependencies and reactive systems. The `on_construct` member function returns a _sink_ (which is an object for connecting and disconnecting listeners) for those interested in notifications when a new instance of a given component type is created: ```cpp // connects a free function registry.on_construct().connect<&my_free_function>(); // connects a member function registry.on_construct().connect<&my_class::member>(instance); // disconnects a free function registry.on_construct().disconnect<&my_free_function>(); // disconnects a member function registry.on_construct().disconnect<&my_class::member>(instance); ``` Similarly, `on_destroy` and `on_update` are used to receive notifications about the destruction and update of an instance, respectively.
Because of how C++ works, listeners attached to `on_update` are only invoked following a call to `replace`, `emplace_or_replace` or `patch`. The function type of a listener is equivalent to the following: ```cpp void(entt::registry &, entt::entity); ``` In all cases, listeners are provided with the registry that triggered the notification and the involved entity. Note also that: * Listeners for the construction signals are invoked **after** components have been assigned to entities. * Listeners designed to observe changes are invoked **after** components have been updated. * Listeners for the destruction signals are invoked **before** components have been removed from entities. There are also some limitations on what a listener can and cannot do: * Connecting and disconnecting other functions from within the body of a listener should be avoided. It can lead to undefined behavior in some cases. * Removing the component from within the body of a listener that observes the construction or update of instances of a given type isn't allowed. * Assigning and removing components from within the body of a listener that observes the destruction of instances of a given type should be avoided. It can lead to undefined behavior in some cases. This type of listeners is intended to provide users with an easy way to perform cleanup and nothing more. Please, refer to the documentation of the signal class to know about all the features it offers.
There are many useful but less known functionalities that aren't described here, such as the connection objects or the possibility to attach listeners with a list of parameters that is shorter than that of the signal itself. ### They call me Reactive System Signals are the basic tools to construct reactive systems, even if they aren't enough on their own. `EnTT` tries to take another step in that direction with the `observer` class template.
In order to explain what reactive systems are, this is a slightly revised quote from the documentation of the library that first introduced this tool, [Entitas](https://github.com/sschmid/Entitas-CSharp): >Imagine you have 100 fighting units on the battlefield but only 10 of them >changed their positions. Instead of using a normal system and updating all 100 >entities depending on the position, you can use a reactive system which will >only update the 10 changed units. So efficient. In `EnTT`, this means to iterating over a reduced set of entities and components with respect to what would otherwise be returned from a view or a group.
On these words, however, the similarities with the proposal of `Entitas` also end. The rules of the language and the design of the library obviously impose and allow different things. An `observer` is initialized with an instance of a registry and a set of rules that describes what are the entities to intercept. As an example: ```cpp entt::observer observer{registry, entt::collector.update()}; ``` The class is default constructible and can be reconfigured at any time by means of the `connect` member function. Moreover, instances can be disconnected from the underlying registries through the `disconnect` member function.
The `observer` offers also what is needed to query the internal state and to know if it's empty or how many entities it contains. Moreover, it can return a raw pointer to the list of entities it contains. However, the most important features of this class are that: * It's iterable and therefore users can easily walk through the list of entities by means of a range-for loop or the `each` member function. * It's clearable and therefore users can consume the entities and literally reset the observer after each iteration. These aspects make the observer an incredibly powerful tool to know at any time what are the entities that matched the given rules since the last time one asked: ```cpp for(const auto entity: observer) { // ... } observer.clear(); ``` The snippet above is equivalent to the following: ```cpp observer.each([](const auto entity) { // ... }); ``` At least as long as the `observer` isn't const. This means that the non-const overload of `each` does also reset the underlying data structure before to return to the caller, while the const overload does not for obvious reasons. The `collector` is a utility aimed to generate a list of `matcher`s (the actual rules) to use with an `observer` instead.
There are two types of `matcher`s: * Observing matcher: an observer will return at least all the living entities for which one or more of the given components have been updated and not yet destroyed. ```cpp entt::collector.update(); ``` _Updated_ in this case means that all listeners attached to `on_update` are invoked. In order for this to happen, specific functions such as `patch` must be used. Refer to the specific documentation for more details. * Grouping matcher: an observer will return at least all the living entities that would have entered the given group if it existed and that would have not yet left it. ```cpp entt::collector.group(entt::exclude); ``` A grouping matcher supports also exclusion lists as well as single components. Roughly speaking, an observing matcher intercepts the entities for which the given components are updated while a grouping matcher tracks the entities that have assigned the given components since the last time one asked.
If an entity already has all the components except one and the missing type is assigned to it, the entity is intercepted by a grouping matcher. In addition, a matcher can be filtered with a `where` clause: ```cpp entt::collector.update().where(entt::exclude); ``` This clause introduces a way to intercept entities if and only if they are already part of a hypothetical group. If they are not, they aren't returned by the observer, no matter if they matched the given rule.
In the example above, whenever the component `sprite` of an entity is updated, the observer probes the entity itself to verify that it has at least `position` and has not `velocity` before to store it aside. If one of the two conditions of the filter isn't respected, the entity is discarded, no matter what. A `where` clause accepts a theoretically unlimited number of types as well as multiple elements in the exclusion list. Moreover, every matcher can have its own clause and multiple clauses for the same matcher are combined in a single one. ## Sorting: is it possible? Sorting entities and components is possible with `EnTT`. In particular, it uses an in-place algorithm that doesn't require memory allocations nor anything else and is therefore particularly convenient.
There are two functions that respond to slightly different needs: * Components can be sorted either directly: ```cpp registry.sort([](const auto &lhs, const auto &rhs) { return lhs.z < rhs.z; }); ``` Or by accessing their entities: ```cpp registry.sort([](const entt::entity lhs, const entt::entity rhs) { return entt::registry::entity(lhs) < entt::registry::entity(rhs); }); ``` There exists also the possibility to use a custom sort function object for when the usage pattern is known. As an example, in case of an almost sorted pool, quick sort could be much slower than insertion sort. * Components can be sorted according to the order imposed by another component: ```cpp registry.sort(); ``` In this case, instances of `movement` are arranged in memory so that cache misses are minimized when the two components are iterated together. As a side note, the use of groups limits the possibility of sorting pools of components. Refer to the specific documentation for more details. ## Helpers The so called _helpers_ are small classes and functions mainly designed to offer built-in support for the most basic functionalities. ### Null entity The `entt::null` variable models the concept of _null entity_.
The library guarantees that the following expression always returns false: ```cpp registry.valid(entt::null); ``` A registry rejects the null entity in all cases because it isn't considered valid. It also means that the null entity cannot own components.
The type of the null entity is internal and should not be used for any purpose other than defining the null entity itself. However, there exist implicit conversions from the null entity to identifiers of any allowed type: ```cpp entt::entity null = entt::null; ``` Similarly, the null entity can be compared to any other identifier: ```cpp const auto entity = registry.create(); const bool null = (entity == entt::null); ``` As for its integral form, the null entity only affects the entity part of an identifier and is instead completely transparent to its version. Be aware that `entt::null` and entity 0 aren't the same thing. Likewise, a zero initialized entity isn't the same as `entt::null`. Therefore, although `entt::entity{}` is in some sense an alias for entity 0, none of them can be used to create a null entity. ### Tombstone Similar to the null entity, the `entt::tombstone` variable models the concept of _tombstone_.
Once created, the integral form of the two values is the same, although they affect different parts of an identifier. In fact, the tombstone only uses the version part of it and is completely transparent to the entity part. Also in this case, the following expression always returns false: ```cpp registry.valid(entt::tombstone); ``` Moreover, users cannot set the tombstone version when releasing an entity: ```cpp registry.destroy(entity, entt::tombstone); ``` In this case, a different version number is implicitly generated.
The type of a tombstone is internal and can change at any time. However, there exist implicit conversions from a tombstone to identifiers of any allowed type: ```cpp entt::entity null = entt::tombstone; ``` Similarly, the tombstone can be compared to any other identifier: ```cpp const auto entity = registry.create(); const bool tombstone = (entity == entt::tombstone); ``` Be aware that `entt::tombstone` and entity 0 aren't the same thing. Likewise, a zero initialized entity isn't the same as `entt::tombstone`. Therefore, although `entt::entity{}` is in some sense an alias for entity 0, none of them can be used to create tombstones. ### To entity Sometimes it's useful to get the entity from a component instance.
This is what the `entt::to_entity` helper does. It accepts a registry and an instance of a component and returns the entity associated with the latter: ```cpp const auto entity = entt::to_entity(registry, position); ``` A null entity is returned in case the component doesn't belong to the registry. ### Dependencies The `registry` class is designed to be able to create short circuits between its functions. This simplifies the definition of _dependencies_ between different operations.
For example, the following adds (or replaces) the component `a_type` whenever `my_type` is assigned to an entity: ```cpp registry.on_construct().connect<&entt::registry::emplace_or_replace>(); ``` Similarly, the code shown below removes `a_type` from an entity whenever `my_type` is assigned to it: ```cpp registry.on_construct().connect<&entt::registry::remove>(); ``` A dependency can also be easily broken as follows: ```cpp registry.on_construct().disconnect<&entt::registry::emplace_or_replace>(); ``` There are many other types of dependencies. In general, most of the functions that accept an entity as the first argument are good candidates for this purpose. ### Invoke Sometimes it's useful to directly invoke a member function of a component as a callback. It's already possible in practice but requires users to _extend_ their classes and this may not always be possible.
The `invoke` helper allows to _propagate_ the signal in these cases: ```cpp registry.on_construct().connect>(); ``` All it does is pick up the _right_ component for the received entity and invoke the requested method, passing on the arguments if necessary. ### Handle A handle is a thin wrapper around an entity and a registry. It provides the same functions that the registry offers for working with components, such as `emplace`, `get`, `patch`, `remove` and so on. The difference being that the entity is implicitly passed to the registry.
It's default constructible as an invalid handle that contains a null registry and a null entity. When it contains a null registry, calling functions that delegate execution to the registry will cause an undefined behavior, so it's recommended to check the validity of the handle with implicit cast to `bool` when in doubt.
A handle is also non-owning, meaning that it can be freely copied and moved around without affecting its entity (in fact, handles happen to be trivially copyable). An implication of this is that mutability becomes part of the type. There are two aliases that use `entt::entity` as their default entity: `entt::handle` and `entt::const_handle`.
Users can also easily create their own aliases for custom identifiers as: ```cpp using my_handle = entt::basic_handle>; using my_const_handle = entt::basic_handle>; ``` Handles are also implicitly convertible to const handles out of the box but not the other way around.
A handle stores a non-const pointer to a registry and therefore it can do all the things that can be done with a non-const registry. On the other hand, const handles store const pointers to registries and offer a restricted set of functionalities. This class is intended to simplify function signatures. In case of functions that take a registry and an entity and do most of their work on that entity, users might want to consider using handles, either const or non-const. ### Organizer The `organizer` class template offers support for creating an execution graph from a set of functions and their requirements on resources.
The resulting tasks aren't executed in any case. This isn't the goal of this tool. Instead, they are returned to the user in the form of a graph that allows for safe execution. All functions are added in order of execution to the organizer: ```cpp entt::organizer organizer; // adds a free function to the organizer organizer.emplace<&free_function>(); // adds a member function and an instance on which to invoke it to the organizer clazz instance; organizer.emplace<&clazz::member_function>(&instance); // adds a decayed lambda directly organizer.emplace(+[](const void *, entt::registry &) { /* ... */ }); ``` These are the parameters that a free function or a member function can accept: * A possibly constant reference to a registry. * An `entt::basic_view` with any possible combination of storage classes. * A possibly constant reference to any type `T` (that is, a context variable). The function type for free functions and decayed lambdas passed as parameters to `emplace` is `void(const void *, entt::registry &)` instead. The first parameter is an optional pointer to user defined data to provide upon registration: ```cpp clazz instance; organizer.emplace(+[](const void *, entt::registry &) { /* ... */ }, &instance); ``` In all cases, it's also possible to associate a name with the task when creating it. For example: ```cpp organizer.emplace<&free_function>("func"); ``` When a function of any type is registered with the organizer, everything it accesses is considered a _resource_ (views are _unpacked_ and their types are treated as resources). The _constness_ of the type also dictates its access mode (RO/RW). In turn, this affects the resulting graph, since it influences the possibility of launching tasks in parallel.
As for the registry, if a function doesn't explicitly request it or requires a constant reference to it, it's considered a read-only access. Otherwise, it's considered as read-write access. All functions will still have the registry among their resources. When registering a function, users can also require resources that aren't in the list of parameters of the function itself. These are declared as template parameters: ```cpp organizer.emplace<&free_function, position, velocity>("func"); ``` Similarly, users can override the access mode of a type again via template parameters: ```cpp organizer.emplace<&free_function, const renderable>("func"); ``` In this case, even if `renderable` appears among the parameters of the function as not constant, it will be treated as constant as regards the generation of the task graph. To generate the task graph, the organizer offers the `graph` member function: ```cpp std::vector graph = organizer.graph(); ``` The graph is returned in the form of an adjacency list. Each vertex offers the following features: * `ro_count` and `rw_count`: they return the number of resources accessed in read-only or read-write mode. * `ro_dependency` and `rw_dependency`: useful for retrieving the type info objects associated with the parameters of the underlying function. * `top_level`: indicates whether a node is a top level one, that is, it has no entering edges. * `info`: returns the type info object associated with the underlying function. * `name`: returns the name associated with the given vertex if any, a null pointer otherwise. * `callback`: a pointer to the function to execute and whose function type is `void(const void *, entt::registry &)`. * `data`: optional data to provide to the callback. * `children`: the vertices reachable from the given node, in the form of indices within the adjacency list. Since the creation of pools and resources within the registry isn't necessarily thread safe, each vertex also offers a `prepare` function which can be called to setup a registry for execution with the created graph: ```cpp auto graph = organizer.graph(); entt::registry registry; for(auto &&node: graph) { node.prepare(registry); } ``` The actual scheduling of the tasks is the responsibility of the user, who can use the preferred tool. ## Context variables Each registry has a _context_ associated with it, which is an `any` object map accessible by both type and _name_ for convenience. The _name_ isn't really a name though. In fact, it's a numeric id of type `id_type` to be used as a key for the variable. Any value is accepted, even runtime ones.
The context is returned via the `ctx` functions and offers a minimal set of feature including the following: ```cpp // creates a new context variable by type and returns it registry.ctx().emplace(42, 'c'); // creates a new named context variable by type and returns it registry.ctx().emplace_as("my_variable"_hs, 42, 'c'); // inserts or assigns a context variable by (deduced) type and returns it registry.ctx().insert_or_assign(my_type{42, 'c'}); // inserts or assigns a named context variable by (deduced) type and returns it registry.ctx().insert_or_assign("my_variable"_hs, my_type{42, 'c'}); // gets the context variable by type as a non-const reference from a non-const registry auto &var = registry.ctx().get(); // gets the context variable by name as a const reference from either a const or a non-const registry const auto &cvar = registry.ctx().get("my_variable"_hs); // resets the context variable by type registry.ctx().erase(); // resets the context variable associated with the given name registry.ctx().erase("my_variable"_hs); ``` The type of a context variable must be such that it's default constructible and can be moved. If the supplied type doesn't match that of the variable when using a _name_, the operation will fail.
For all users who want to use the context but don't want to create elements, the `contains` and `find` functions are also available: ```cpp const bool contains = registry.ctx().contains(); const my_type *value = registry.ctx().find("my_variable"_hs); ``` Also in this case, both functions support constant types and accept a _name_ for the variable to look up, as does `at`. ### Aliased properties Context variables can also be used to create aliases for existing variables that aren't directly managed by the registry. In this case, it's also possible to make them read-only.
To do that, the type used upon construction must be a reference type and an lvalue is necessarily provided as an argument: ```cpp time clock; registry.ctx().emplace