I have a need to clone a derived class given only a reference or pointer to the base class. The following code does the job, but doesn\'t seem elegant, because I\'m putting
You can rely on the CRTP idiom.
It follows a minimal, working example:
struct B {
~virtual ~B() { }
virtual B* clone() = 0;
};
template
struct D: public B {
B* clone() {
return new C{*static_cast(this)};
}
};
struct S: public D { };
int main() {
B *b1 = new S;
B *b2 = b1->clone();
delete b1;
delete b2;
}