C++ C++;在公共容器中存储子对象
我在名称空间中有一组抽象父类,类似于以下内容C++ C++;在公共容器中存储子对象,c++,oop,C++,Oop,我在名称空间中有一组抽象父类,类似于以下内容 namespace Core { class Sparse; class Dense; } 我在某个地方定义了这些类,然后派生了一些子类: class SparseA: public Core::Sparse; class SparseB: public Core::Sparse; class DenseA: public Core::Dense; 现在我想实例化子类的一些对象,并将它们存储在一个可以从任何地方访问的公共容器中。我
namespace Core {
class Sparse;
class Dense;
}
我在某个地方定义了这些类,然后派生了一些子类:
class SparseA: public Core::Sparse;
class SparseB: public Core::Sparse;
class DenseA: public Core::Dense;
现在我想实例化子类的一些对象,并将它们存储在一个可以从任何地方访问的公共容器中。我该怎么做
还有一个问题:我是否也应该在核心命名空间中包含子类
谢谢。
< P>长类<代码>稀疏和 无关,不能将派生类的实例存储在同一个C++标准容器中(除非你将使用这样的花哨的东西,如<代码> Boo::变体或<代码> Boo::任何< /COD>)。
如果给它们一个公共(抽象)基类,则可以使用智能指针(例如std::unique_ptr
或std::shared_ptr
)在容器中不断引用它们(使用与示例中相同的伪语法)
名称空间核心{
类公共基;
类稀疏:公共公共基;
类密集:公共公共基础;
}
typedef-std::载体型支原体;
另一个选项可能是模板包装类解决方案
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>>());
名称空间核心{
类包装器库{
公众:
//将稀疏和密集的公共接口公开为
//纯虚函数
虚拟void foo()=0;
虚拟~WrapperBase(){}
};
模板
类包装器:公共包装器库{
私人:
Impl&Impl;
公众:
包装器(Impl&Impl):Impl(Impl){}
void foo(){
impl.foo();//委托给实际实现
}
};
类稀疏;
类密;
}
typedef-std::载体型支原体;
支原体型容器;
container.push_back(std::make_unique());
container.push_back(std::make_unique());
container.push_back(std::make_unique());
后者允许在单个容器中松散耦合类,如Sparse
和densite
,但至少需要一些抽象接口,可以对这两个类及其派生的类使用行为一致的接口。是否要在容器中混合稀疏和密集?如果是这样,你确定这就是你想要的设计吗?boost::variant
@KarolyHorvath这可能是另一个问题。我可能需要也可能不需要这些对象,因此我将动态创建它们(在类似于每个对象的工厂中),并需要在控制台对象中访问所有对象,因此我考虑将它们存储在同一个位置。你还有其他的设计建议吗?我对这个领域一无所知,不知道什么是Console或Dense,也不知道你在做什么。提出任何设计都是不明智的。@Manattta像这样一个完全通用的问题的问题是,唯一真正的答案是完全通用的答案“视情况而定”。这是一个好的设计吗?或者你有更好的建议吗?@manatttta“这是一个好的设计吗?”嗯,这取决于你想用它解决什么问题。至少它是有效的和健壮的。
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>>());