我有一个基类,其中有许多派生类。然而,它是指向基类的指针,存储在我的程序的容器中,因此它可以迭代并调用它们上的虚拟函数。
我有另一个类将基类指针添加到此容器中,因此当派生类被新建
(而不是裸露)时,它们必须返回或存储为基类类指针。
我正在考虑使用模板创建一个简单的基类工厂方法来为我执行此操作:
template<class T> //T is the derived class
static T* Factory(){
return static_cast<T*>(functionThatAddsBaseClassPointerToContainer(new T));
}
我看到两个主要优点/缺点:
优点:不需要为每个派生类重写它
缺点:通过将不是从我的基派生的类类型传递为 T
可能会被错误使用。
有没有办法确保T
是在这个函数Factory
内部派生的?或者我可以期望编译器捕获未派生 T
的实例吗?
这种通用方法是可以接受的想法吗,还是有更好的替代方案?
最佳答案
Is there a way to ensure that T is derived inside this function Factory?
如果functionThatAddsBaseClassPointerToContainer
采用Base*
,则已经完成。
Base* functionThatAddsBaseClassPointerToContainer(Base* b); // <--
template<class T> //T is the derived class
static T* Factory(){
// if T was not derived from Base, the following line fails to compile:
return static_cast<T*>(functionThatAddsBaseClassPointerToContainer(new T));
}
关于c++ - 在派生类上使用工厂方法的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16663526/