[英](C++ inheritance) storing objects with common parent in stl container
[英]C++ Storing child objects in a common container
我在命名空间中有一组抽象父类,类似于以下内容
namespace Core {
class Sparse;
class Dense;
}
我在某处定义了这些类,之后我派生了一些子类:
class SparseA: public Core::Sparse;
class SparseB: public Core::Sparse;
class DenseA: public Core::Dense;
现在我想实例化子类的一些对象,并将它们存储在一个可以从任何地方访问的公共容器中。 我怎样才能做到这一点?
另一个问题:我是否应该在Core
命名空间中包含子类?
谢谢。
由于Sparse
和Dense
这些长类是无关的,所以你不能将派生类的实例存储在同一个c ++标准容器中(除非你要使用像boost::variant
或boost::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>>());
后者将允许在单个容器中松散地耦合像Sparse
和Dense
这样的类,但仍然至少需要一些抽象接口,可以对两个类和从它们派生的类使用行为一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.