3
일부 기본 추상 형식에서 파생 된 개체를 저장하기 위해 boost에서 ptr_map을 사용하고 있습니다.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의이 참조를 반환! 그래서 constructur에서 값에서 유형을 호출 할 수 있습니다. 이제 컴파일러는 오류와 함께 실패 값에 대한 포인터를 반환 ptr_map 어떤 방법이
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’
경우, 어떤 문제가있을 수 woudln't. 이것에 대해 뭐라 할 수 있니?
아마 : operator []는 키가 아닌 값/객체를 인스턴스화합니다. 또한, 핵심은 여기서 추상적이지 않습니다. –