您可以使用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
你試圖定義一個單/工廠? – Shoe
不是一個單身人士。我不確定是否可以使用工廠解決問題? –