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
To achieve clone that works as with covariant return type, there is a need for some more complicated CRTP:
class Shape {
// virtual
virtual Shape* do_clone() const = 0;
public:
virtual ~Shape() {}
// non-virtual
Shape* clone() const {
return do_clone();
}
// ...
};
template
class CloneCRTP : public Base {
// virtual
Shape* do_clone() const override {
return new Derived(static_cast(*this));
}
public:
// non-virtual
Derived* clone() const {
return static_cast(do_clone());
}
};
Usage:
class Rectangle: public CloneCRTP { /*...*/ };
class Triangle: public CloneCRTP { /*...*/ };
int main() {
Rectangle* r1 = new Rectangle{};
// getting the proper type from clone:
Rectangle* rcopy = r1->clone();
delete rcopy;
delete r1;
Triangle t1{};
// getting the proper type from clone:
Triangle* tcopy = t1.clone();
delete tcopy;
}
Code: http://coliru.stacked-crooked.com/a/d8781deee5f7f6ea