设计在C++中的容器中一起使用所有子类

Mer*_*rni 2 c++ templates

我刚读了一篇关于奇怪的重复模板模式的文章.您可以使用它模拟模板的虚拟功能.

例如:

template<class T>
struct A
{
    void func() { static_cast<T*>(this)->func(); }
};

struct B : public A<B>
{
    void func() { cout << "B" << endl; }
};`
Run Code Online (Sandbox Code Playgroud)

但是,如果我们有来自A的许多子类并希望将它们全部放在向量中,例如,vector<A*>当您使用模板时,这是不可能的,并且您必须在基类中使用普通的多态与虚函数.

解决这个问题的设计建议是什么?因为我想使用模板,但也能够在容器中一起使用所有子类.

Mar*_*n B 5

你可以这样做:

class NonTemplateBase
{
};

template<class T>
struct A : public NonTemplateBase
{
    void func() { static_cast<T*>(this)->func(); }
};
Run Code Online (Sandbox Code Playgroud)

然后创建一个指针向量NonTemplateBase(即std::vector<NonTemplateBase *>).

但是,我猜你想要能够func()在向量中的对象上调用或使用其他成员函数 - 并且您希望这些调用以多态方式调用派生类中的正确成员函数.

这不会起作用,因为奇怪的重复模板模式只允许你做静态(即编译时)多态.如果您想要运行时多态性,则必须使用虚函数.