What are some 'good use' examples of dynamic casting?

后端 未结 6 2258
攒了一身酷
攒了一身酷 2020-12-09 03:29

We often hear/read that one should avoid dynamic casting. I was wondering what would be \'good use\' examples of it, according to you?

Edit:

Yes, I\'m aware

6条回答
  •  忘掉有多难
    2020-12-09 03:38

    My current toy project uses dynamic_cast twice; once to work around the lack of multiple dispatch in C++ (it's a visitor-style system that could use multiple dispatch instead of the dynamic_casts), and once to special-case a specific subtype.

    Both of these are acceptable, in my view, though the former at least stems from a language deficit. I think this may be a common situation, in fact; most dynamic_casts (and a great many "design patterns" in general) are workarounds for specific language flaws rather than something that aim for.

提交回复
热议问题