Browse Source

added get overload with default value to registry (#152)

Michele Caini 7 years ago
parent
commit
0ced60e712
2 changed files with 38 additions and 2 deletions
  1. 32 0
      src/entt/entity/registry.hpp
  2. 6 2
      test/entt/entity/registry.cpp

+ 32 - 0
src/entt/entity/registry.hpp

@@ -675,6 +675,38 @@ public:
         }
     }
 
+    /**
+     * @brief Returns a reference to the given component for an entity.
+     *
+     * In case the entity doesn't own the component, the value provided will be
+     * used to construct it.<br/>
+     * Equivalent to the following snippet (pseudocode):
+     *
+     * @code{.cpp}
+     * auto &component = registry.has<Component>(entity) ? registry.get<Component>(entity) : registry.assign<Component>(entity, value);
+     * @endcode
+     *
+     * Prefer this function anyway because it has slightly better performance.
+     *
+     * @warning
+     * Attempting to use an invalid entity results in undefined behavior.<br/>
+     * An assertion will abort the execution at runtime in debug mode in case of
+     * invalid entity.
+     *
+     * @tparam Component Type of component to get.
+     * @param entity A valid entity identifier.
+     * @param component Instance to use to construct the component.
+     * @return Reference to the component owned by the entity.
+     */
+    template<typename Component>
+    Component & get(const entity_type entity, Component &&component) ENTT_NOEXCEPT {
+        assert(valid(entity));
+        assure<Component>();
+        auto &cpool = pool<Component>();
+        auto *comp = cpool.try_get(entity);
+        return comp ? *comp : cpool.construct(entity, std::forward<Component>(component));
+    }
+
     /**
      * @brief Returns pointers to the given components for an entity.
      *

+ 6 - 2
test/entt/entity/registry.cpp

@@ -157,13 +157,17 @@ TEST(Registry, Functionalities) {
 
     const auto e3 = registry.create();
 
-    registry.assign<int>(e3);
-    registry.assign<char>(e3);
+    ASSERT_EQ(registry.get<int>(e3, 3), 3);
+    ASSERT_EQ(registry.get<char>(e3, 'c'), 'c');
 
     ASSERT_EQ(registry.size<int>(), entt::registry<>::size_type{1});
     ASSERT_EQ(registry.size<char>(), entt::registry<>::size_type{1});
     ASSERT_FALSE(registry.empty<int>());
     ASSERT_FALSE(registry.empty<char>());
+    ASSERT_TRUE(registry.has<int>(e3));
+    ASSERT_TRUE(registry.has<char>(e3));
+    ASSERT_EQ(registry.get<int>(e3), 3);
+    ASSERT_EQ(registry.get<char>(e3), 'c');
 
     ASSERT_NO_THROW(registry.reset<int>());