Curiously recurring template pattern: Difference between revisions

Content deleted Content added
Updated code to C++11 standard
Polymorphic copy construction: Modernized code example
Line 210:
<source lang="cpp">
// Base class has a pure virtual function for cloning
class ShapeAbstractShape {
public:
virtual ~ShapeAbstractShape () = default;
virtual ShapeAbstractShape *clone() const = 0;
};
// This CRTP class implements clone() for Derived
template <typename Derived>
class Shape_CRTPShape : public ShapeAbstractShape {
public:
Shapestd::unique_ptr<AbstractShape> *clone() const override{
return new Derived(static_cast<Derived const&>(*this));
}
 
protected:
// We make clear Shape Class need to be inherited
Shape() = default;
Shape(const Shape&) = default;
};
 
// Every derived class inherits from Shape_CRTPCRTP class instead of Shapeabstract class
// Nice macro which ensures correct CRTP usage
 
#define Derive_Shape_CRTP(Type) class Type: public Shape_CRTP<Type>
class Square : public Shape<Square>{};
 
class Circle: public Shape<Square>{};
 
// Every derived class inherits from Shape_CRTP instead of Shape
Derive_Shape_CRTP(Square) {};
Derive_Shape_CRTP(Circle) {};
</source>