基本抽象型から派生したオブジェクトを格納するために、boostのptr_mapを使用しています。
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
挿入はうまく機能します:
someMap.insert("someKey", new Entity1());
someMap.insert("someKey", new Entity2());
しかし、マップから戻っていない:
template<typename EntityType>
EntityType *GetEntity(const string &entityName)
{
return dynamic_cast<EntityType*>(&someMap[entityName]);
}
GetEntity<Entity1>(entityName);
ここで問題:ptr_mapのoperator []が参照を返します!したがって、コンストラクターでは、値から型を呼び出すことができます。コンパイラはエラーで失敗します:
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’
値へのポインタを返すメソッドがptr_mapにある場合、問題はありません。これについて何と言えますか?