Re: What's polymorphic in CRTP
On Monday, February 11, 2013 5:38:03 PM UTC+1, =D6=F6 Tiib wrote:
On Monday, 11 February 2013 17:40:04 UTC+2, Jarek Blakarz wrote:
Hi
I understand what is CRTP. What I don't understand is why CRTP is calle=
d a
static polymorphism or rather polymorphism in particular.
It is not called static polymorphism. It is common technique in C++ to ac=
hieve
static polymorphism.
I think that it is "static" since the function call is resolved at comp=
ile
time, right ?
Yes. You are correct. Exactly like there are arrays with static size
(std::array<T,N>) and dynamic size (std::vector<T>). Static size means lo=
st
flexibility (that is maybe not needed) and won efficiency (that is always
great to have).
Assuming that I'm right about "static", plese explain me based on the=
following example why it is "polymorphic".
template <class Derived> struct Base {
void interface() { static_cast<Derived*>(this)->implementation(); }
This may or not be bare-bone interface. This is basic part of implementat=
ion
that calls possibly "statically overriden" member function from derived c=
lass.
You can even provide default implementation here:
void implementation() { }
};
struct Derived1 : Base<Derived1> {
void implementation() { }
};
struct Derived2 : Base<Derived2> {
void implementation() { }
};
Lets take you have default and also such Derived3 here:
struct Derived3 : Base<Derived3> {
};
Derived1 *d1 = new Derived1;
Derived2 *d2 = new Derived2;
d1->interface();
d2->interface();
Your example leaks memory and feels like Java with its tons of news at
each corner. C++11 just forgot to add 'std::make_unique<T>()', if that
was in language then need to write 'new' or 'delete' in C++ code was
close to none.
Derived1 d1;
Derived2 d2;
Derived3 d3;
d1.interface();
d2.interface();
d3.interface();
It is polymorphism. All 3 calls may do different things. All 3 calls have
part (possibly everything) of what they do inherited from Base, and part
(possibly nothing) overriden. All 3 calls have exactly same common user
interface.
It is subtly less flexible and more efficient than virtual call ... so
better *you* explain ... what is your problem of calling it polymorphism?
Thanks for explanation to everyone.
My goal was just to understand why it is called polymorphism.
Earlier I only suspected why. Now I think I got it.