فهرست منبع

added registry::accomodate

Michele Caini 9 سال پیش
والد
کامیت
40368941d6
3فایلهای تغییر یافته به همراه16 افزوده شده و 0 حذف شده
  1. 1 0
      README.md
  2. 9 0
      src/registry.hpp
  3. 6 0
      test/registry.cpp

+ 1 - 0
README.md

@@ -175,6 +175,7 @@ Once you have created a registry, the followings are the exposed member function
 * `has<Components...>(entity)`: returns `true` if the entity has the given components, `false` otherwise.
 * `get<Component>(entity)`: returns a reference to the given component for the entity (undefined behaviour if the entity has not the component).
 * `replace<Component>(entity, args...)`: replaces the given component for the entity, using `args...` to create the new component.
+* `accomodate<Component>(entity, args...)`: replaces the given component for the entity if it exists, otherwise assigns it to the entity and uses `args...` to initialize it.
 * `clone(entity)`: clones an entity and all its components, then returns the new entity identifier.
 * `copy<Component>(from, to)`: copies a component from an entity to another one (both the entities must already have been assigned the component, undefined behaviour otherwise).
 * `copy(from, to)`: copies all the components and their contents from an entity to another one (comoonents are created or destroyed if needed).

+ 9 - 0
src/registry.hpp

@@ -325,6 +325,15 @@ public:
         pool.template get<Comp>(entity) = Comp{args...};
     }
 
+    template<typename Comp, typename... Args>
+    void accomodate(entity_type entity, Args... args) {
+        if(pool.template has<Comp>(entity)) {
+            this->template replace<Comp>(entity, std::forward<Args>(args)...);
+        } else {
+            this->template assign<Comp>(entity, std::forward<Args>(args)...);
+        }
+    }
+
     entity_type clone(entity_type from) {
         auto to = create();
         using accumulator_type = int[];

+ 6 - 0
test/registry.cpp

@@ -67,6 +67,12 @@ TEST(DefaultRegistry, Functionalities) {
     ASSERT_EQ(registry.get<int>(e2), 0);
     ASSERT_NE(&registry.get<int>(e1), &registry.get<int>(e2));
 
+    ASSERT_NO_THROW(registry.remove<int>(e2));
+    ASSERT_NO_THROW(registry.accomodate<int>(e1, 1));
+    ASSERT_NO_THROW(registry.accomodate<int>(e2, 1));
+    ASSERT_EQ(registry.get<int>(e1), 1);
+    ASSERT_EQ(registry.get<int>(e2), 1);
+
     ASSERT_EQ(registry.size(), registry_type::size_type{3});
     ASSERT_EQ(registry.capacity(), registry_type::size_type{3});
     ASSERT_FALSE(registry.empty());