added get_or_assign (close #202)

This commit is contained in:
Michele Caini
2019-03-12 14:50:47 +01:00
parent 0d22da672d
commit dcbf6e43c7
3 changed files with 9 additions and 7 deletions

View File

@@ -10,6 +10,7 @@ ceeac
corystegel
Croydon
dbacchet
dBagrat
djarek
DonKult
drglove

View File

@@ -788,16 +788,17 @@ public:
* invalid entity.
*
* @tparam Component Type of component to get.
* @tparam Args Types of arguments to use to construct the component.
* @param entity A valid entity identifier.
* @param component Instance to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return Reference to the component owned by the entity.
*/
template<typename Component>
Component & get(const entity_type entity, Component &&component) ENTT_NOEXCEPT {
template<typename Component, typename... Args>
Component & get_or_assign(const entity_type entity, Args &&... args) ENTT_NOEXCEPT {
assert(valid(entity));
auto *cpool = assure<std::remove_reference_t<Component>>();
auto *comp = cpool->try_get(entity);
return comp ? *comp : cpool->construct(entity, std::forward<Component>(component));
return comp ? *comp : cpool->construct(entity, std::forward<Args>(args)...);
}
/**

View File

@@ -160,8 +160,8 @@ TEST(Registry, Functionalities) {
const auto e3 = registry.create();
ASSERT_EQ(registry.get<int>(e3, 3), 3);
ASSERT_EQ(registry.get<char>(e3, 'c'), 'c');
ASSERT_EQ(registry.get_or_assign<int>(e3, 3), 3);
ASSERT_EQ(registry.get_or_assign<char>(e3, 'c'), 'c');
ASSERT_EQ(registry.size<int>(), entt::registry<>::size_type{1});
ASSERT_EQ(registry.size<char>(), entt::registry<>::size_type{1});
@@ -1197,7 +1197,7 @@ TEST(Registry, Clone) {
TEST(Registry, GetOrAssign) {
entt::registry<> registry;
const auto entity = registry.create();
const auto value = registry.get<int>(entity, 3);
const auto value = registry.get_or_assign<int>(entity, 3);
ASSERT_TRUE(registry.has<int>(entity));
ASSERT_EQ(registry.get<int>(entity), value);
ASSERT_EQ(registry.get<int>(entity), 3);