Passing a derived class into a map c++ -
what place manager map, , call functions correlating each manager. because have different types of managers created base class so:
class igyromanager { public: igyromanager() {} virtual ~igyromanager() = default; virtual bool preinit() = 0; virtual bool init() = 0; virtual bool postinit() = 0; virtual void update() = 0; virtual void cleanup() = 0; }
pretty straight forward , works charm.
then following create derived class:
class gyroaudiomanager : public igyromanager { public: gyroaudiomanager(); ~gyroaudiomanager() override; bool preinit() override; bool init() override; bool postinit override; void update() override; bool cleanup() override; }
again, simple , straight forward. cpp basic , declares bare functions.
i create 1 final derived class:
class gyroappstatemanager : igyromanager { private: std::map<int, igyromanager&> m_managermap; public: gyroappstatemanager(); ~gyroappstatemanager() override; bool preinit() override; bool init() override; bool postinit() override; int start(); void update() override; bool registermanager(igyromanager& manager); bool cleanup() override; }
that seems work, it's in registermanager function falls apart:
bool gyroappstatemanager::registermanager(igyromanager& manager) { // try insert derived class base class map using // should working. m_managermap.insert(1, manager); return true; }
and in calling function:
int start() { gyroaudiomanager m_audiomanager = gyroaudiomanager(); mp_appstatemanager->registermanager(m_audiomanager); /* use mp_appstatemanager here, while m_audiomanager alive */ }
except not seem work @ , spits out following:
error: no matching function call std::map<int, igyromanager&>::insert(int, igyromanager&)
so question doing wrong? mentioned above, i'd add multiple different manager classes derive single base class map , able run functions it.
is there way of doing it?
you can't have standard container of references. i'm still looking exact wording of restriction, in meantime might want try std::reference_wrapper
instead, or container of (smart) pointers, allows polymorphism.
actually, value_type
std::pair<key_type, mapped_type>
object type when mapped_type
reference. that's ok.
the error caused because parameter std::map<key,value>::insert
pair<key,value>
, not 2 separate arguments. try
m_managermap.insert({1, manager});
but need arrange reference object isn't destroyed afterward, when start()
returns.
Comments
Post a Comment