简体   繁体   English

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

[英]C++ Storing child objects in a common container

I have a set of abstract parent classes in a namespace, similar to the following 我在命名空间中有一组抽象父类,类似于以下内容

namespace Core {
    class Sparse;
    class Dense;
}

I define those classes somewhere and after that I derive some child classes: 我在某处定义了这些类,之后我派生了一些子类:

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

Now I want to instantiate some objects of the child classes and store them in a common container that can be accessible from anywhere. 现在我想实例化子类的一些对象,并将它们存储在一个可以从任何地方访问的公共容器中。 How can I do this? 我怎样才能做到这一点?

And another question: Should I include the child classes in the Core namespace aswell? 另一个问题:我是否应该在Core命名空间中包含子类?

Thank you. 谢谢。

As long classes Sparse and Dense are unrelated, you can't store instances of derived classes in the same c++ standard container (unless you're going to use such fancy stuff as boost::variant or boost::any ). 由于SparseDense这些长类是无关的,所以你不能将派生类的实例存储在同一个c ++标准容器中(除非你要使用像boost::variantboost::any这样的花哨的东西)。

If you give them a common (abstract) base class you can use smart pointers ( eg std::unique_ptr<> or std::shared_ptr ) to keep referencing them in a container (using the same pseudo syntax as in your sample) 如果你给它们一个公共(抽象)基类,你可以使用智能指针(例如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;

Another option might be a template wrapper class solution 另一个选项可能是模板包装类解决方案

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>>());

The latter will allow to loosely couple classes like Sparse and Dense within a single container, but still at least requires some abstract interface, that could be be used behaviorally consistent for both classes, and classes derived from them. 后者将允许在单个容器中松散地耦合像SparseDense这样的类,但仍然至少需要一些抽象接口,可以对两个类和从它们派生的类使用行为一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM