Let's suppose there is a base object class - let it be called Object - and a list<Object> container. There are many child classes of Object - Child1, Child2 etc.. They all are stored in the container.
I need a way to iterate over subsets of objects of some particular class. Say, over all Child1's or Child2's, while having them all together in one container so that they could be accessed in a polymorphic fashion.
Note should be taken that the container is dynamically resized now and then.
What are possible design solutions for that?
Currently I've come up with two:
- introducing an iterator which runs on the container checking object type each time
- keeping additional containers with all Child1 and all Child2 objects from the main container.
Honestly, I don't like either way: the first one, I'm afraid, is going to be slow because there will be really many objects, the second one is clumsy and requires observing each object addition and deletion.
I'm writing it in C++.
UPDATE
As a further development of the second solution, I've just thought of subclassing a list with methods that would return sublists of particular subclass types which could be kept cached and updated on each add/delete:
for(auto i: gameObjects.sublist<Child1>()) {
...