Re: What's polymorphic in CRTP
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 called a
static polymorphism or rather polymorphism in particular.
It is not called static polymorphism. It is common technique in C++ to achieve
static polymorphism.
I think that it is "static" since the function call is resolved at compile
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 lost
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 implementation
that calls possibly "statically overriden" member function from derived class.
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?