0

I have the following structs:

struct IAnimateAction{};
struct AnimateActions {
    int mSec;
    std::vector<IAnimateAction> actions;
};

struct ZoomAction : public IAnimateAction {
    explicit ZoomAction(int targetZoom);
    int targetZoom;
};
struct TranslateAction : public IAnimateAction{
    TranslateAction(int targetX, int targetY);
    int targetX;
    int targetY;
};
struct TurnAction: public IAnimateAction {
    explicit TurnAction(float targetAngle);
    float targetAngle; //radials
};

A ZoomAction and TranslateAction can be combined inside the AnimateActions like this:

AnimateActions actions;
actions.mSec = 5000;
actions.actions.push_back(ZoomAction(130));
actions.actions.push_back(TurnAction(270));
c.animatelist.push(actions);

This will tell my animation system to both do a 'zoom' and 'turn' action in 5 seconds. (The std::vector can probably just be a simple array I just realized)..

They are stored in std::queue<AnimateActions> animatelist;.

But I'm stuck on retrieving them, how would I know which type of struct I'm retrieving? I want my IDE to give me typehints for the specific struct I'm handling, in this loop:

if (!animatelist.empty()) {
    auto element = animatelist.front();
    for (auto action : elelement.actions) {
        //cast to specific struct?
    }
    animatelist.pop();
}
Oli
  • 2,370
  • 2
  • 26
  • 42
  • Nothing is going to work until you change `std::vector actions;` to use some kind of pointer type, e.g. `std::vector actions;` or preferably a smart pointer e.g. `std::vector> actions;` Your code at present is suffering from *object slicing*. – john Aug 09 '22 at 09:51
  • One somewhat messy solution (eg what MS does in COM for Outlook, Task Scheduler etc) is to have a `IAnimateAction::Type()` function in the base class, together with an enum of `ACTION_TYPE` (say). Then a `switch` statement to cast the `IAnimateAction` pointer to a concrete type. It is messy from an encapsulation point of view (ie IAnimateAction needs to know all the possible derived types). Each derived class implements the `Type()` function using the enum in the base class. – DS_London Aug 09 '22 at 09:51
  • Once you have solved the object slicing problem, the usual way to handle this situation in C++ is to use *virtual functions* to discriminate between the different types you have in your vector. – john Aug 09 '22 at 09:54
  • I'll read up a bit on object slicing, and see what I can achieve with pointers! – Oli Aug 09 '22 at 10:02

0 Answers0