Hacker News new | ask | show | jobs
by emilern 1336 days ago
The enum example in the article
1 comments

OK, that's an interesting language feature, but I can't say it's something that I've often wanted to do in C++. Of course C++ does have std::variant and std::any, although I'm not really a fan. I'd tend to (and have) just use a class that contains the variants and an enum to track which one, then setters and getters.

event.SetKeyPress(ch);

event.SetMouseButtonPress(pos, but); etc

...

switch (event.type) {

case EvKeyPress: ch = event.GetKeyPress();

Of course the Rust features being used by that Event type are runtime polymorphism and type introspection, so another obvious C++ approach would be just to use a pointer to a virtual based class including the type, then:

switch (event->type) {

case EvKeyPressEvent:

  {

    auto kpe - dynamic_cast<KeyPressEvent*>(event)

    ...

  }

  break;

}