如何实现 Copying derived entities using only base class pointer

#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\n";
    }   
};

struct D2 : Cloneable<D2> {
    D2() {}
    D2(const D2& other) {
        std::cout << "Copy constructing D2\n";
    }   
};


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&> 注意这里,因为函数的参数就是引用,所以这里转换成引用

 

posted @ 2015-01-20 11:15  穆穆兔兔  阅读(178)  评论(0编辑  收藏  举报