#include <iostream> struct CloneableBase { virtual CloneableBase* clone() const = 0; }; template<class Derived> struct Cloneable : CloneableBase { virtual CloneableBase* clone() const { return new Derived(static_cast<const Derived&>(*this)); } }; struct D1 : Cloneable<D1> { D1() {} D1(const D1& other) { std::cout << "Copy constructing D1 "; } }; struct D2 : Cloneable<D2> { D2() {} D2(const D2& other) { std::cout << "Copy constructing D2 "; } }; int main() { CloneableBase* a = new D1(); CloneableBase* b = a->clone(); CloneableBase* c = new D2(); CloneableBase* d = c->clone(); }
http://stackoverflow.com/questions/5027456/copying-derived-entities-using-only-base-class-pointers-without-exhaustive-tes
static_cast<const Derived&> 注意这里,因为函数的参数就是引用,所以这里转换成引用