and Merry Christmas everybody!
I am learning about static polymorphism and I'm reading Andrei Alexandrescu's excellent book on policy-based design. I came across the following, in my code: I have interface Interface
which specifies that method Foo
must be present. This interface will be implemented by class Impl
. I have the following two options:
1) Dynamic polymorphism
class Interface {
public:
virtual void Foo() = 0;
}
class Impl : public Interface {
public:
void Foo() {};
}
2) Static polymorphism
class Impl {
{
public:
void Foo() {};
}
template <class I>
class Interface : public I
{
public:
void Foo() { I::Foo(); } //not actually needed
}
Does it make sense to use static polymorphism in this case? Does the second approach offer any benefits compared to the first one? The interface specifies only the presence of some methods, and its mechanics are the same for different implementation - so not quite like the cases described in the book, so I feel I may only be over-complicating things.
Update: I do not need polymorphic behaviour at run-time; the correct implementation is known at compile-time.
Checking Interface.
Dynamic polymorphism does force the child to respect the interface.
Static polymorphism does NOT force the child to respect the interface (until you really call the function), So, if you don't provide useful method, you may use directly
Impl
.You have a 3rd way using traits to check that a class verify an Interface:
With C++20 concepts, traits can be written differently:
Lets test it:
Performance
With Dynamic Polymorphism, you may pay for virtual call. You may reduce some virtual call by adding
final
asclass Child final : public Interface
.So compiler may optimize code like:
but it can't do any magic (assuming
bar
not inlined) with:Now, assume that in your interface you have:
we are in the second case where we have to virtual call
Foo
.Static polymorphism solves that by: