C++ Polymorphism - Map of inherited classes -
i have movementsystem
class inherits system
class. later have number of xxxsystem
classes store instances of xxxsystem
(there 1 instance per system) in map way:
enum { movement_system }; std::map<int,std::unique_ptr<system>> systems; systems[movement_system] = std::unique_ptr<system>(new movementsystem()); m_entitymanager.loadsystems(&systems);
the last line there because need class entitymanager
have access systems.
therefore have method:
std::map<int,std::unique_ptr<system>> *m_systems; // line in header void entitymanager::loadsystems(std::map<int,std::unique_ptr<system>> *systems) { m_systems = systems; }
and in other method of entitymanager
try access systems have sent class way:
std::unique_ptr<movementsystem> mvt = (*m_systems)[movement_system]; mvt->update(dt);
but error:
conversion 'std::map<int, std::unique_ptr<system> >::mapped_type {aka std::unique_ptr<system>}' non-scalar type 'std::unique_ptr<movementsystem>' requested
how can fix , last line call update method movementsystem
?
std::unique_ptr<movementsystem> mvt = *m_systems[movement_system];
there 2 problems line. one, operator precedence such interpreted this:
*(m_systems[movement_system])
this means apply pointer arithmetic pointer m_systems
(accessing movement-system
th element in "array" pointed m_systems
) , apply *
map, nonsense. wanted this:
(*m_systems)[movement_system]
the second problem you're trying copy unique pointer. precisely unique pointers designed prevent.
what want pointer, , cast accordingly:
movementsystem *mvt = static_cast<movementsystem*>((*m_systems)[movement_system].get());
or, better because gets rid of unnecessary pointers:
auto &systems = *m_systems; auto &mvt = static_cast<movementsystem&>(*systems[movement_system]); mvt.update(dt);
Comments
Post a Comment