Why is 'pure polymorphism' preferable over using RTTI?

前端 未结 7 705
清歌不尽
清歌不尽 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:31

    If you call a function, as a rule you don't really care what precise steps it will take, only that some higher-level goal will be achieved within certain constraints (and how the function makes that happen is really it's own problem).

    When you use RTTI to make a preselection of special objects that can do a certain job, while others in the same set cannot, you are breaking that comfortable view of the world. All of a sudden the caller is supposed to know who can do what, instead of simply telling his minions to get on with it. Some people are bothered by this, and I suspect this is a large part of the reason why RTTI is considered a little dirty.

    Is there a performance issue? Maybe, but I've never experienced it, and it might be wisdom from twenty years ago, or from people who honestly believe that using three assembly instructions instead of two is unacceptable bloat.

    So how to deal with it... Depending on your situation it might make sense to have any node-specific properties bundled into separate objects (i.e. the entire 'orange' API could be a separate object). The root object could then have a virtual function to return the 'orange' API, returning nullptr by default for non-orange objects.

    While this might be overkill depending on your situation, it would allow you to query on root level whether a specific node supports a specific API, and if it does, execute functions specific to that API.

提交回复
热议问题