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:
- 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)
- It's make me uncomfortable to state a
elsestatement, since the compiler knows the type, theelsestatement acts very similar to thedefaultstatement in an enum switch-case statement, that is, if every case is listed, thedefault caseis useless, and if not every case is listed while nodefault caselisted, the compiler will warn me. I think this rule also fits to thedynamic_castcases.
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