I’m curious what constructs or language features, available in both the current C++ as well as in C++11, can be used to deduce the type of an object. An example:
class Base {
};
class DerivA
: public Base {
};
class DerivB
: public Base {
};
void foo(Base* obj) {
// Identify if `obj` is a `DerivA` or a `DerivB`
}
This is an oversimplification. It would appear that rather than having a way to identify the type, the best solution is to have overloads of the function for the two derived types and do away with the base class.
My real use case is one where one class is not interested in the exact type of the object (ie. just needs an implementation of Base) and another class needs to know exactly what implementation of Base the first class is using.
This happens in a component-based game entity system. The base would be an EntityState and its derived types are StandingState, DeadState, etc. Class Entity is the one that only needs a generic EntityState object and class EntityRepresentation needs to know exactly what state the entity is in to decide whether to draw the “standing” animation or the “dead” animation, or whatever.
Edit: Of course, if possible, I’d like to implement the game in such a way that not even the entity representation needs to know the type of the entity state. If there’s a way to do that, then I’d use it. 🙂 I’ll look into the visitor pattern.
You can use
dynamic_castfor that: