Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to clone a polymorphic object without manually adding overridden clone method into each derived class in C++?

Tags:

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++?

like image 923
Calmarius Avatar asked Mar 09 '19 10:03

Calmarius


1 Answers

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.

like image 196
n. 1.8e9-where's-my-share m. Avatar answered Oct 06 '22 14:10

n. 1.8e9-where's-my-share m.