c++ - Design pattern for accessing non-const through a const intermediate -
can suggest better design situation want 2 objects "talk" each other through const intermediate.
here contrived example, 2 players trade lemons. player finds player in "world", "world" should const, since player shouldn't able modify (lets deleting walls).
void player::give_lemon() { const world& world = this->get_world(); const player& other = world.get_nearest_player(*this); this->lemons--; other.lemons++; // error } what designs people use, simple const_cast easy dirty. or provide way of "looking up" non-const player reference, lets having access non-const player_list() here we'd duplicating functionality available in world, possibly less efficiently, round-about way of doing specific const_cast.
it seems both player , world can seen actors
world happens const
introduce manager class handles both:
manager take const world in constructor , players can added or removed.
void player::give_lemon() { manager& mgr = this->get_manager(); player& other = mgr.get_nearest_player(*this); this->lemons--; other.lemons++; // error } the manager keeps track of positions of players in world. world const , cannot have mutable list of players, manager can.
Comments
Post a Comment