Dyamic vs Static Polymorphism in C++ : which is preferable?

前端 未结 4 1301
孤城傲影
孤城傲影 2020-12-25 14:44

I understand that dynamic/static polymorphism depends on the application design and requirements. However, is it advisable to ALWAYS choose static polymorphism over dynamic

4条回答
  •  感情败类
    2020-12-25 14:56

    You see the design issues associated with purely template based polymorphism. While a looking virtual base class gives you a pretty good idea what is expected from a derived class, this gets much harder in heavily templated designs. One can easily demonstrate that by introducing a syntax error while using one of the boost libraries.

    On the other hand, you are fearful of performance issues when using virtual functions. Proofing that this will be a problem is much harder.

    IMHO this is a non-question. Stick with virtual functions until indicated otherwise. Virtual function calls are a lot faster than most people think (Calling a function from a dynamically linked library also adds a layer of indirection. No one seems to think about that).

    I would only consider a templated design if it makes the code easier to read (generic algorithms), you use one of the few cases known to be slow with virtual functions (numeric algorithms) or you already identified it as a performance bottleneck.

提交回复
热议问题