The typical pattern when you want to copy a polymorphic class is adding a virtual clone method and implement it in each derived class like this:
Base* Derived::clone() { return new Derived(*this); }
Then in a calling code you can:
Base *x = new Derived(); Base *y = x->clone();
However if you have 50+ derived classes and realize you need polymorphic copy, it's tedious to copy-paste the cloning method into each of them. And it's essentially a boilerplate that works around a language limitation that you have to spell out the actual name to call the constructor.
I haven't keep track with the new features in recent C++ standards... Is there a way to avoid this in modern C++?
You can use this generic CRTP code
template <class Derived, class Base> struct Clonable : Base { virtual Base* do_clone() { return new Derived(*static_cast<Derived*>(this)); } Derived* clone() { // not virtual return static_cast<Derived*>(do_clone()); } using Base::Base; }; struct empty {}; struct A : Clonable<A, empty> {}; struct B : Clonable<B, A> {};
It can be generalised to smart pointers and multiple bases if desired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With