vendredi 9 août 2019

Is it possible to create a datatype that could represent multiple structs in c++?

Essentially I am creating a wrapper for SDL which is a media layer library for c++. I want my application to be able to create event watchers (like javascript's addEventListener()). I have several different event structs for different kinds of events as shown below. Is it possible to create a datatype called Event, that could be passed to a user defined handler function that would have the appropriate struct data.

struct MouseEvent {
    EventType type;
    int x;
    int y;
    uint8_t which;
    bool down;
};
struct KeyboardEvent {
    EventType type;
    int keyCode;
    const char* key;
    bool lshift;
    bool rshift;
    bool lctrl;
    bool rctrl;
    bool lalt;
    bool ralt;
    bool lmeta;
    bool rmeta;
    bool numlock;
    bool capslock;
    bool ctrl;
    bool shift;
    bool alt;
    bool meta;
};
struct WindowEvent {
    EventType type;
};
struct WheelEvent {
    EventType type;
    int x;
    int y;
    bool dir;
};

So for further explanation here is an example: the use clicks, so that creates a MouseEvent and passes that MouseEvent as an Event type to a function that checks for mousedown listeners. Is this a good way of doing this or am I just stupid.

I have looked into unions however when you use a union if a user wanted to access data within the event they would have to do something like event.mouse.x when I would much prefer it be accessed by just event.x Maybe I am just too picky

Aucun commentaire:

Enregistrer un commentaire