jeudi 18 avril 2019

How to use polymorphism to apply the same operation to unordered_sets with different objects that have the same base class?

I have:

std::unordered_set<ui::Button*> _buttons;
std::unordered_set<Sprite*> _sprites; 

Both ui::Button and Sprite, inherit from Node.

So for example, I can do:

for(Node* node : _sprites){
    node->setPosition(1,2); 
}

for(Node* node : _buttons){
    node->setPosition(1,2);
}

Since I need to do the same operations on both sets, is there some way do this with just one loop ?

I have to maintain sprites and buttons in two separate sets.

Can I do something like this:

std::unordered_set<std::unordered_set<Node*>> mySets;
mySets.insert(_buttons); 
mySets.insert(_sprites);

for(auto mySet : mySets)
    for(Node* node : mySet){
        node->setPosition(1,2);
    }
}

Aucun commentaire:

Enregistrer un commentaire