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.
CRTP and static polymorphism
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...