CRTP

posted Feb 21, 2012, 7:21 AM by Nico Kruithof
The curiously recurring template pattern (http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) is a nice way to implement common functionality that would normally belong in a base class. The advantage is that it doesn't require virtual functions which are normally used to delegate functionality to the child class.

An example is a singleton class:

template <class Derived>
class Singleton
{
public:
    /// Allocates the singleton on first request.
    static Derived &get();

protected:
    Singleton();
    ~Singleton();

private:
    static tbb::spin_mutex m_singleton_mutex;

    static Derived *s_singleton;
};

class Derived : public Singleton<Derived>
{
private:
    friend class Singleton<Derived>;
    Derived();
};

Comments