Ptr_map and pointer

I use ptr_map from boost to store objects derived from a base abstract type.

class Entity { virtual void foo() = 0; };
class Entity1 : public Entity {};
class Entity2 : public Entity {};

boost::ptr_map<string, Entity> someMap; // We could store pointers for abstract type

The insert works great:

someMap.insert("someKey", new Entity1());
someMap.insert("someKey", new Entity2());

But without returning from the map:

template<typename EntityType>
EntityType *GetEntity(const string &entityName)
{
    return dynamic_cast<EntityType*>(&someMap[entityName]);
}

GetEntity<Entity1>(entityName);

Now the problem: the [] ptr_map operator returns a link! Thus, in the constructor there may be a type of call from a value. Now the compiler has an error:

 instantiated from ‘EntityType* EntityManager::GetEntity(const std::string&) [with EntityType = Entity1, std::string = std::basic_string<char>]’
error: cannot allocate an object of abstract type ‘Entity’

If ptr_map has any method that returns a pointer to a value, there will not be any problems. What can you say about this?

+3
source share
1 answer

, [] , . , . at().

return dynamic_cast<EntityType*>(&someMap.at(entityName));

": "

, , , - .

+4

Source: https://habr.com/ru/post/1751989/


All Articles