CRTP and static polymorphism
Since CRTP allows us to override base class functions with those of the derived class, it implements polymorphic behavior. The key difference is that polymorphism happens at compile time, not at runtime.
Compile-time polymorphism
As we have just seen, CRTP can be used to allow the derived class to customize the behavior of the base class:
template <typename D> class B { public: ... void f(int i) { static_cast<D*>(this)->f(i); } protected: int i_; }; class D : public B<D> { public: void f(int i) { i_ += i; } };
If the base class B::f()
method is called, it dispatches the call to the derived class method for the real derived class, just like a virtual function does. Of course, in order to fully take advantage of this polymorphism, we have to be able to call the methods of the base class through the base class pointer. Without this ability,...