Avoiding dynamic_cast/RTTI

前端 未结 6 767
执笔经年
执笔经年 2020-12-16 23:13

I was recently working on a piece of C++ code for a side project (the cpp-markdown library, for the curious), and ran into a coding question that I\'d like some opinions on.

6条回答
  •  攒了一身酷
    2020-12-17 00:06

    #1 pollutes the class namespace and vtable for objects that don't need it. Ok when you have a handful of methods that will generally be implemented, but plain ugly when only needed for a single derived class.

    #2 is just dynamic_cast<> in a polka-dot dress and lipstick. Doesn't make client code any simpler, and tangles up the entire hierarchy, requiring the base and each derived class to be semi-aware of every other derived class.

    Just use dynamic_cast<>. That's what it's there for.

提交回复
热议问题