Curiously recurring template pattern: Difference between revisions

Content deleted Content added
Static polymorphism: minor error, wrong function name
m adjust heading levels to make it logically correct
Line 239:
This allows obtaining copies of squares, circles or any other shapes by <code>shapePtr->clone()</code>.
 
===Pitfalls===
One issue with static polymorphism is that without using a general base class like <code>AbstractShape</code> from the above example, derived classes cannot be stored homogeneously--that is, putting different types derived from the same base class in the same container. For example, a container defined as <code>std::vector<Shape*></code> does not work because <code>Shape</code> is not a class, but a template needing specialization. A container defined as <code>std::vector<Shape<Circle>*></code> can only store <code>Circle</code>s, not <code>Square</code>s. This is because each of the classes derived from the CRTP base class <code>Shape</code> is a unique type. A common solution to this problem is to inherit from a shared base class with a virtual destructor, like the <code>AbstractShape</code> example above, allowing for the creation of a <code>std::vector<AbstractShape*></code>.