Why is 'pure polymorphism' preferable over using RTTI?

前端 未结 7 670
清歌不尽
清歌不尽 2020-12-04 08:59

Almost every C++ resource I\'ve seen that discusses this kind of thing tells me that I should prefer polymorphic approaches to using RTTI (run-time type identification). In

相关标签:
7条回答
  • 2020-12-04 09:34

    It looks kind of neat in a small example, but in real life you will soon end up with a long set of types that can poke each other, some of them perhaps only in one direction.

    What about dark_orange_node, or black_and_orange_striped_node, or dotted_node? Can it have dots of different colors? What if most dots are orange, can it be poked then?

    And each time you have to add a new rule, you will have to revisit all the poke_adjacent functions and add more if-statements.


    As always, it is hard to create generic examples, I'll give you that.

    But if I were to do this specific example, I would add a poke() member to all the classes and let some of them ignore the call (void poke() {}) if they are not interested.

    Surely that would be even less expensive than comparing the typeids.

    0 讨论(0)
提交回复
热议问题