Browse Source

added registry::ctx_or_set

Michele Caini 6 years ago
parent
commit
526814b9ed
2 changed files with 19 additions and 2 deletions
  1. 17 0
      src/entt/entity/registry.hpp
  2. 2 2
      test/entt/entity/registry.cpp

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

@@ -1633,6 +1633,23 @@ public:
         }), vars.end());
     }
 
+    /**
+     * @brief Binds an object to the context of the registry.
+     *
+     * In case the context doesn't contain the given object, the parameters
+     * provided are used to construct it.
+     *
+     * @tparam Type Type of object to set.
+     * @tparam Args Types of arguments to use to construct the object.
+     * @param args Parameters to use to initialize the object.
+     * @return Reference to the object.
+     */
+    template<typename Type, typename... Args>
+    Type & ctx_or_set(Args &&... args) {
+        auto *type = try_ctx<Type>();
+        return type ? *type : set<Type>(std::forward<Args>(args)...);
+    }
+
     /**
      * @brief Returns a pointer to an object in the context of the registry.
      * @tparam Type Type of object to get.

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

@@ -43,7 +43,7 @@ TEST(Registry, Context) {
 
     registry.set<char>();
     registry.set<int>();
-    registry.set<double>();
+    registry.ctx_or_set<double>();
 
     ASSERT_NE(registry.try_ctx<char>(), nullptr);
     ASSERT_NE(registry.try_ctx<int>(), nullptr);
@@ -61,7 +61,7 @@ TEST(Registry, Context) {
     registry.set<double>(1.);
     registry.set<int>(42);
 
-    ASSERT_EQ(registry.ctx<char>(), 'c');
+    ASSERT_EQ(registry.ctx_or_set<char>('a'), 'c');
     ASSERT_NE(registry.try_ctx<char>(), nullptr);
     ASSERT_EQ(registry.try_ctx<char>(), &registry.ctx<char>());
     ASSERT_EQ(registry.ctx<char>(), std::as_const(registry).ctx<char>());