Avoiding dynamic_cast/RTTI

前端 未结 6 779
执笔经年
执笔经年 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:10

    If you want to get clever, you could also build a double dispatch pattern, which is two-thirds of the visitor pattern.

    • Create a base TokenVisitor class containing empty virtual visit(SpecificToken*) methods.
    • Add a single virtual accept(TokenVisitor*) method to Token that calls the properly-typed method on the passed TokenVisitor.
    • Derive from TokenVisitor for the various things you will need to do in varying ways over all tokens.

    For the full visitor pattern, useful for tree structures, have the default accept methods iterate over children calling token->accept(this); on each.

提交回复
热议问题