c ++ Object创建相同类型的新实例

时间:2014-04-10 19:34:44

标签: c++ object types instantiation

有没有办法让对象有可能创建它自己的类型的新对象,而不指定这种类型?

class Foo {
public:
    virtual Foo* new_instance() {
        return new type_of(this); // Some magic here
    }
};

class Bar: public Foo {

};

Foo* a = new Foo();
Foo* b = new Bar();
Foo* c = a->new_instance();
Foo* d = b->new_instance();

我现在希望c属于Foo类型,而d应该属于Bar类型。

4 个答案:

答案 0 :(得分:5)

简短的回答:不,没有办法让这种魔法发生。

您可以使用宏来更轻松地覆盖子类中的函数,或者创建一个使用“奇怪的重复模板模式”的中间类:

template <typename T>
class FooDerived : public Foo
{
public:
    T* new_instance() {
        return new T();
    }
};

class Bar : public FooDerived<Bar>
{
};

Foo* a = new Bar();
Foo* b = a->new_instance(); // b is of type Bar*

但这绝对不值得付出努力。

答案 1 :(得分:1)

直截了当的解决方案:

class Foo {
public:
    virtual Foo* new_instance() {
        return new Foo();
    }
};

class Bar: public Foo {
public:
    virtual Foo* new_instance() {
        return new Bar();
    }
};

答案 2 :(得分:1)

您可以使用Mixin添加工厂类。对于工厂功能而言似乎相当复杂,当然难以理解。

#include <typeinfo>
#include <cassert>
#include <iostream>

template<class T> class WithFactory: public T {
public:
    WithFactory<T>* new_instance() override {
        return new WithFactory<T>( );
    }
};

class FactoryFunction {
    virtual FactoryFunction* new_instance() = 0;
};

class Foo_: public FactoryFunction {
public:
    virtual void f() {
        std::cout << "Foo" << std::endl;
    }
};
typedef WithFactory<Foo_> Foo;

class Bar_: public Foo {
public:
    virtual void f() override {
        std::cout << "Bar" << std::endl;
    }
};
typedef WithFactory<Bar_> Bar;

int main()
{
    Foo* a = new Foo();
    Foo* b = new Bar();
    Foo* c = a->new_instance();
    Foo* d = b->new_instance();

    assert( typeid(a) == typeid(c) );
    assert( typeid(b) == typeid(d) );

    a->f();
    b->f();
    c->f();
    d->f();

    return 0;
}

输出

Foo
Bar
Foo
Bar

答案 3 :(得分:0)

是的,你只需要它

virtual Foo* new_instance() { return new Foo(); }

然后在每个派生类中再次重载它以执行相同的操作(虽然我更喜欢模板方法来处理这类事情)