简体   繁体   中英

Can I achieve all the functionality of dynamic polymorphism with static polymorphism?

I am used to use dynamic polymorphism and everything works fine but after reading about static polymorphism I concluded that this latter overcomes the overheads of dynamic one.

Here are some overhead of dynamic polymorphism:

  • Extra indirection (pointer dereference) for each call to a virtual method.

  • Virtual methods usually can't be inlined, which may be a significant cost hit for some small methods.

  • Additional pointer per object. On 64-bit systems which are prevalent these days, this is 8 bytes per object. For small objects that carry little data this may be a serious overhead.

Can anyone explains to me Static polymorphism with a very simple example. And when cases I should use it instead of the dynamic one?

I found this example but sorry I don't understand it. It looks ambiguous:

#include <iostream>
using namespace std;

template <typename Child>
struct Base
{
    void interface()
    {
        static_cast<Child*>(this)->implementation();
    }
};

struct Derived : Base<Derived>
{
    void implementation()
    {
        cerr << "Derived implementation\n";
    }
};

int main()
{
    Derived d;
    d.interface();  // Prints "Derived implementation"
}

Let's first analyze what will happen after compiling code you sent. Compiler will generate two classes, and inside of method interface, it will just move pointer to address where object of Derived located and will call method implementation with that pointer.

So now only overhead we have, is that we should generate more classes for each derived class (I mean binary code).

What you are missing now?

Consider following code:

Base* base;

if(a)
  base = new DerivedA;
else
  base = new DerivedB;

base->interface();

The value of variable a is only known at runtime, so you can only use dynamic polymorphism for it.

If it was static polymorphism, you should have told what will be type of derived class.

Base<DerivedA> * base;
Base<DerivedB> * base;

Which not allows you to decide for it, dependent on runtime context.

Static polymorphism is an alternative name for function overloading. This is a convenience feature, which lets you avoid renaming a function simply to take an alternative set of parameters.

It is completely orthogonal to dynamic polymorphism, which is an actual dispatch mechanism, when the function is decided at run-time.

Note: the overhead of dynamic polymorphism is so small that you should not consider it until you profile the program and see that the overhead is significant. This happens very infrequently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM