pattern to avoid dynamic_cast

后端 未结 2 1968
忘掉有多难
忘掉有多难 2021-01-31 05:35

I have a class:

class A 
{
public:
  virtual void func() {…}
  virtual void func2() {…}
};

And some derived classes from this one, lets say B,C,D

2条回答
  •  没有蜡笔的小新
    2021-01-31 05:56

    Someone intelligent (unfortunately I forgot who) once said about OOP in C++: The only reason for switch-ing over types (which is what all your suggestions propose) is fear of virtual functions. (That's para-paraphrasing.) Add virtual functions to your base class which derived classes can override, and you're set.
    Now, I know there are cases where this is hard or unwieldy. For that we have the visitor pattern.

    There's cases where one is better, and cases where the other is. Usually, the rule of thumb goes like this:

    • If you have a rather fixed set of operations, but keep adding types, use virtual functions.
      Operations are hard to add to/remove from a big inheritance hierarchy, but new types are easy to add by simply having them override the appropriate virtual functions.

    • If you have a rather fixed set of types, but keep adding operations, use the visitor pattern.
      Adding new types to a large set of visitors is a serious pain in the neck, but adding a new visitor to a fixed set of types is easy.

    (If both change, you're doomed either way.)

提交回复
热议问题