C++将子对象存储在公共容器中
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
等类,但至少仍然需要一些抽象接口,这些接口可以在行为上一致地用于两个类以及从它们派生的类。
相关文章:
- C++ 在堆栈中包含多态属性的类对象存储
- 将对象存储为其基本虚拟类
- 将大型对象存储在无序映射中是否效率低下
- C++:将未知类型的对象存储为成员变量的类
- 按unique_pointer将传递的对象存储在地图中
- 如何将 c++ 类对象存储为数组?
- 将对象存储在 std::map 中
- 是否存在对象存储在其生存期内可能会更改的情况?
- 将不同类型的对象存储在容器中
- 将自定义可绘制对象存储在数组中会导致绘制时出现分割错误
- 我将如何在C++中文件处理对象(存储/导入)
- 将对象存储在C 中的2维Sprite矩阵中
- 将抽象派生类对象存储在基类向量中
- 将任意函数对象存储到类成员容器中,而无需知道其声明签名
- 如何使用向量将类对象存储在超载操作员中
- 适当的方法将对象存储在Std矢量中
- 将向量对象存储在共享指针投掷错误中
- 将多态对象存储在unordered_set中
- 为什么我可以将对象存储在大小不同的数组中
- 返回对象存储在哪里