I want to store objects relative to their type.
I have a Status
class which is inherited to create different status such as Burn
, Stun
, etc...
I would like to store statuses in sets with a set for each type (a character can a multiple burn status at once, so I want to get the set storing all the burn statuses but not other statuses).
my solutions so far looks like this
std::map<std::type_index, std::set<Status*>> statuses;
// access all Burn statuses
for (const Burn* b : statuses.find(typeid(Burn))->second) {} // error : E0144 a value of type "Status *" cannot be used to initialize an entity of type "const DamageModifier *"
**
However this is downcasting and the compiler doesn't want it to work.
My questions are as follow:
Status
subclass.The problem was that I tried to do two things at once from my last code version
std::set<Status*>
to std::map<std::typeid, std::set<Status*>>
which is OK as long as you cast the result the same as beforeBoth answer helped me realise the problem was that I tried to do both at once.
How could I access a set and downcast it to the right type without copying
You can use static_cast
to down cast:
for (const Status* s : statuses.find(typeid(Burn))->second) {
auto b = static_cast<const Burn*>(s);
}
You must be very careful though to not insert pointers to wrong derived classes into wrong set. That will silently pass compilation and break at runtime (if you're lucky).