dimanche 8 décembre 2019

enum switch-case style dynamic_cast

Is there any design pattern which uses dynamic_cast the way like use a switch-case statement?

In practice, when I use dynamic_cast like this:

  if (auto *type1 = dynamic_cast<Foo *>(&base)) {

  } else if (auto *type2 = dynamic_cast<Bar *>(&base)) {

  } else {
    throw WtfException();
  }

I think there's two problems with this:

  1. if I got types other than two, the if-else statement may effect the performance(compared with switch-case statement of which most implementations are used hash map)
  2. It's make me uncomfortable to state a else statement, since the compiler knows the type, the else statement acts very similar to the default statement in an enum switch-case statement, that is, if every case is listed, the default case is useless, and if not every case is listed while no default case listed, the compiler will warn me. I think this rule also fits to the dynamic_cast cases.

So is there any design pattern which can make the use of dynamic_cast as if using the enum switch-case style?

Aucun commentaire:

Enregistrer un commentaire