多态和指针向量的C ++问题 [英] c++ problem with polymorphism and vectors of pointers
问题描述
考虑以下示例代码:
class Foo
{
};
class Bar : public Foo
{
};
class FooCollection
{
protected:
vector<shared_ptr<Foo> > d_foos;
};
class BarCollection : public FooCollection
{
public:
vector<shared_ptr<Bar> > &getBars()
{
// return d_foos won't do here...
}
};
我当前的项目中遇到这样的问题.客户端代码使用BarCollection
,它在FooCollection
中声明的d_foos
中存储指向Bars
的指针.现在,我想向客户代码公开指向Bars的指针的集合.我可以让客户端代码访问指向Foo
的指针的向量,并将其转换为客户端代码中指向Bar
的指针,但是这感觉很不对劲,因为客户端不必了解Foo
的存在.
I have a problem like this in my current project. The client code uses BarCollection
, which stores pointers to Bars
in d_foos
which is declared in FooCollection
. I'd now like to expose the collection of pointers to Bars to the client code. I could just give the client code access to the vector of pointers to Foo
s and cast these to pointers to Bar
s in the client code, but this feels wrong since the client doesn't have to know about Foo
's existence.
我还可以定义一个get()
成员,该成员从d_foos
检索对象并将其强制转换,但这感觉很笨拙.最好是,我只想将d_foos作为vector<shared_ptr<Bar> > &
返回,但是我似乎无法做到这一点.
I could also define a get()
member that retrieves objects from d_foos
and casts them, but this feels quite clumsy. Preferably, I'd like to just return d_foos as a vector<shared_ptr<Bar> > &
, but I cannot seem to do this.
也可能是我的设计完全错误.不过,这似乎是最自然的解决方案,因为Bar
是Foo
的专业化,而BarCollection
是FooCollection
的专业化,并且它们共享功能.
It could also be that my design is just plain wrong. It seemed to most natural solution though, as Bar
is a specialization of Foo
and BarCollection
is a specialization of FooCollection
and they share functionality.
您能建议在BarCollection
中实现getBars
的更好解决方案还是更好的设计替代方案?
Could you suggest nice solutions to implement getBars
in BarCollection
or better design alternatives?
结果证明我的设计确实很糟糕.尽管需要所有FooCollection的功能,BarCollection也不是FooCollection.我当前基于以下答案的解决方案-更干净-现在是:
Turns out my design was bad indeed. BarCollection is not a FooCollection, despite of requiring all of FooCollection's functionality. My current solution based on the answers below -- which is a lot cleaner -- is now:
class Foo
{
};
class Bar : public Foo
{
};
template<class T>
class Collection
{
vector<shared_ptr<T> > d_items;
};
typedef Collection<Foo> FooCollection;
class BarCollection : public Collection<Bar>
{
// Additional stuff here.
};
感谢所有出色的建议和示例!
Thanks for all the excellent suggestions and examples!
推荐答案
template<class T>
class MyContainer {
vector<shared_ptr<T> > d_foos;
public:
vector<shared_ptr<T> > & getVector();
};
class FooCollection : public MyContainer<Foo> {
};
class BarCollection : public MyContainer<Bar> {
};
这篇关于多态和指针向量的C ++问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!