c++对象创建相同类型的新实例
c++ Object creating new instances of same type
有没有一种方法可以让对象在不指定该类型的情况下创建自己类型的新对象?
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
类型。
简短的回答:不,没有办法让这种魔法发生。
您可以使用宏使覆盖子类中的函数变得更容易,或者创建一个使用"奇怪的重复模板模式"的中间类:
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*
但这肯定不值得付出努力。
直接解决方案:
class Foo {
public:
virtual Foo* new_instance() {
return new Foo();
}
};
class Bar: public Foo {
public:
virtual Foo* new_instance() {
return new Bar();
}
};
您可以使用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
是的,你只需要做
virtual Foo* new_instance() { return new Foo(); }
然后在每个派生类中,您再次重载它以执行相同的操作(尽管我更喜欢模板方法而不是这种方法)
相关文章:
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 根据参数创建派生类的新实例
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- 基于现有实例创建类的新实例
- 将unordered_map的新实例插入到unordered_map中
- 如何自动生成结构的新实例
- 在C 中,是否有一种(新的)方法来测试类是否在模板中具有虚拟破坏者而无需实例化实例
- 如何使递归函数在进入下一级循环之前读取每个新实例
- 为什么方法应该返回新实例,而不是修改实例本身
- C 函数中的新实例
- 正确的编码:返回类的新实例时
- 如果我在一个类中有一个静态属性,并创建该类的许多新实例
- 在 C 中声明结构的新实例
- 如何检查是否存在单例实例,如果没有,则不创建新实例?
- malloc是否创建该类的新实例
- 返回矢量的新实例
- "错误:需要类型"创建新实例
- 如何防止其他人在堆上创建类的新实例
- 使用模板创建类的新实例,不知道如何处理错误
- 尝试使用模板创建类的新实例,意外错误