CRTP For Static Polymorphism

The curiously recurring template pattern [] is characterised by a class D which derives from an instantiation of a template class B<D>:


struct D : public B<D>
{
};

The CRTP allows for static polymorphism. In the following example the base class is able to call method g() in any derived class even though there are no virtual functions:


template<class T>
struct Base
{
    void f()
    {
        static_cast<T*>(this)->g();
    }
};
struct Derived1 : public Base<Derived1>
{
    void g();
};
struct Derived2 : public Base<Derived2>
{
    void g();
};