/* Cloneable template class protects a derived object from slicing when used with stl containers Author: Jesse van den Kieboom Jesse provides the following example based on his class template Cloneable: vector > vec; vec.push_back(B()); vec.push_back(B()); Cloneable a = B(); a->(functie op A/B) Cloneable b = B(); a = b; */ #ifndef __CLONEABLE_H__ #define __CLONEABLE_H__ namespace jessevdk { template class Cloneable { Base *d_base; public: /* Default constructor */ Cloneable(); template Cloneable(Cloneable const &other); /* Specialisation needed to override default copy constructor */ Cloneable(Cloneable const &other); template Cloneable(Other const &other); /* Deconstructor */ virtual ~Cloneable(); /* Public functions */ template Cloneable &operator=(Cloneable const &other); /* Specialisation needed to override default assignment operator */ Cloneable &operator=(Cloneable const &other); template Cloneable &operator=(Other const &other); /* Operators */ Base &operator*(); Base const &operator*() const; Base *operator->(); Base const *operator->() const; operator Base&(); private: /* Private functions */ void destroy(); template Cloneable &assign(Other const &other); }; /* Constructors */ template inline Cloneable::Cloneable() { d_base = new Base(); } template template inline Cloneable::Cloneable(Other const &other) { /* Clone other */ d_base = other.clone(); } template inline Cloneable::Cloneable(Cloneable const &other) { /* Clone other from cloneable */ d_base = other->clone(); } template template inline Cloneable::Cloneable(Cloneable const &other) { /* Clone other from cloneable */ d_base = other->clone(); } /* Destructor */ template inline Cloneable::~Cloneable() { destroy(); } template template Cloneable& Cloneable::assign(Other const &other) { /* Assign other to this cloneable with self-destroy check */ if (d_base != &other) { destroy(); d_base = other.clone(); } return *this; } template Cloneable& Cloneable::operator=(Cloneable const &other) { return assign(*other); } template template Cloneable& Cloneable::operator=(Cloneable const &other) { return assign(*other); } template template Cloneable& Cloneable::operator=(Other const &other) { return assign(other); } template inline void Cloneable::destroy() { delete d_base; } /* Operators */ template inline Base &Cloneable::operator*() { return *d_base; } template inline Base *Cloneable::operator->() { return d_base; } template inline Base const &Cloneable::operator*() const { return *d_base; } template inline Base const *Cloneable::operator->() const { return d_base; } template inline Cloneable::operator Base&() { return *d_base; } } #endif /* __CLONEABLE_H__ */