C++将子对象存储在公共容器中

C++ Storing child objects in a common container

本文关键字:对象 存储 C++      更新时间:2023-10-16

我在一个命名空间中有一组抽象父类,类似于下面的

namespace Core {
    class Sparse;
    class Dense;
}

我在某个地方定义了这些类,然后派生出一些子类:

class SparseA: public Core::Sparse;
class SparseB: public Core::Sparse;
class DenseA: public Core::Dense;

现在,我想实例化子类的一些对象,并将它们存储在一个可以从任何地方访问的公共容器中。我该怎么做?

还有一个问题:我是否也应该将子类包括在Core命名空间中?

谢谢。

由于长类SparseDense是不相关的,您不能将派生类的实例存储在同一个c++标准容器中(除非您要使用boost::variantboost::any之类的花哨的东西)。

如果你给它们一个通用(抽象)基类,你可以使用智能指针(例如std::unique_ptr<>std::shared_ptr)在容器中不断引用它们(使用与示例中相同的伪语法)

namespace Core {
    class CommonBase;
    class Sparse : public CommonBase;
    class Dense : public CommonBase;
}
typedef std::vector<std::unique_ptr<Core::CommonBase>> MyContainerType;

另一种选择可能是模板包装类解决方案

namespace Core {
    class WrapperBase {
    public:
        // Expose the common interface of Sparse and Dense as
        // pure virtual functions
        virtual void foo() = 0;
        virtual ~WrapperBase() {}            
    };
    template<class Impl>
    class Wrapper : public WrapperBase {
    private:
         Impl& impl_;
    public:
         Wrapper(Impl& impl) : impl_(impl) {}
         void foo() {
             impl.foo(); // Delegate to the actual implementation
         }
    };
    class Sparse;
    class Dense;
}
typedef std::vector<std::unique_ptr<Core::WrapperBase>> MyContainerType;
MyContainerType container;
container.push_back(std::make_unique<Wrapper<SparseA>>());
container.push_back(std::make_unique<Wrapper<SparseB>>());
container.push_back(std::make_unique<Wrapper<DenseA>>());

后者将允许在单个容器中松散地耦合SparseDense等类,但至少仍然需要一些抽象接口,这些接口可以在行为上一致地用于两个类以及从它们派生的类。