Thursday, March 11, 2010

Curious

In designs that use the curiously recurring template pattern, the base class usually needs access to the derived class. Typically this is done by casting the base class's this pointer. This technique is encapsulated in the curious class below. Simply derive the base class from curious to inherit a derived() member function that returns a pointer to the derived class.

template<class Derived>
class curious {
protected:

  typedef Derived derived_type;

  derived_type* derived()
  {
    return static_cast<derived_type*>(this);
  }

  derived_type const* derived() const
  {
    return static_cast<derived_type const*>(this);
  }
};

No comments:

Post a Comment