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

我怕爱的太早我们不能终老 提交于 2019-12-02 19:12:23

A switch is nothing more than a sequence of jumps that -after optimized- becomes a jump to an address looked-up by a table. Exactly like a virtual function call is.

If you have to jump depending on a type, you must first select the type. If the selection cannot be done at compile time (essentially because it depends on the input) you must always perform two operation: select & jump. The syntactic tool you use to select doesn't change the performance, since optimize the same.

In fact you are reinventing the v-table.

Static and dynamic polymorphism are designed to solve different problems, so there are rarely cases where both would be appropriate. In such cases, dynamic polymorphism will result in a more flexible and easier to manage design. But most of the time, the choice will be obvious, for other reasons.

One rough categorisation of the two: virtual functions allow different implementations for a common interface; templates allow different interfaces for a common implementation.

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.

Static polimorphism may provide significant advantage if the called method may be inlined by compiler. For example, if the virtual method looks like this:

protected:
virtual bool is_my_class_fast_enough() override {return true;}

then static polimophism should be the preferred way (otherwise, the method should be honest and return false :).

"True" virtual call (in most cases) can't be inlined.

Other differences(such as additional indirection in the vtable call) are neglectable

[EDIT]

However, if you really need runtime polymorphism (if the caller shouldn't know the method's implementation and, therefore, the method can't be inlined on the caller's side) then do not reinvent vtable (as Emilio Garavaglia mentioned), just use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!