c++ - 在派生类上使用工厂方法的模板

标签 c++ polymorphism

我有一个基类,其中有许多派生类。然而,它是指向基类的指针,存储在我的程序的容器中,因此它可以迭代并调用它们上的虚拟函数。

我有另一个类将基类指针添加到此容器中,因此当派生类被新建(而不是裸露)时,它们必须返回或存储为基类类指针。

我正在考虑使用模板创建一个简单的基类工厂方法来为我执行此操作:

    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/

相关文章:

c++ - 使用声明的可 rebase 类无法在 MSVC 中编译

c++ - 我该如何创建一个类,以对对象进行类型删除,直到调用了一个函数,而没有事先指定可能的函数列表?

c++ - 简单多态

oop - 在 Haskell 中创建绑定(bind)到记录的方法

haskell - GHC 扩展的语义允许对方法进行限制 (-XConstrainedClassMethods)

c++ - Minimax 算法究竟是如何工作的?

c++ - 为什么VC++/MFC没有main函数?

c++ - 查找 vector 是否为子 vector C++

c++ - 如何在 C++ 中检查多个文件是否有重复项

java - java中通过流实现对象的多态性?