将派生类列表传递给需要 C++ 中基类列表的函数;
我有以下课程
class Parent {
virtual void doStuff() = 0;
};
class Child : public Parent {
void doStuff() {
// Some computation here
}
};
并且我有一个具有以下签名的函数。
void computeStuff(std::vector<boost::shared_ptr<Parent> >);
假设我可以重构我的代码(包括函数签名),向函数 computeStuff
传递指向 Child
对象的指针列表的最佳方式是什么?
上,我希望编译并运行以下代码片段
std::vector<boost::shared_ptr<Child> > listOfChilds = getList();
computeStuff(listOfChilds);
I have the following classes
class Parent {
virtual void doStuff() = 0;
};
class Child : public Parent {
void doStuff() {
// Some computation here
}
};
And I have a function with the following signature.
void computeStuff(std::vector<boost::shared_ptr<Parent> >);
Provided I can refactor my code (including the function signature), what is the best way to pass the function computeStuff
a list of pointers to Child
objects?
Essentially, I would like the following snippet of code to compile and run
std::vector<boost::shared_ptr<Child> > listOfChilds = getList();
computeStuff(listOfChilds);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“最好”的方法是让函数采用一对迭代器:
您可以将此函数称为:
采用一对迭代器而不是容器有很多优点,但这里的两个大优点是
该范围只需包含可转换为您想要使用的类型的对象(例如
boost::shared_ptr
),它实际上不必包含该特定类型的对象。The "best" way would be to have the function take a pair of iterators:
You can call this function as:
There are a lot of advantages to taking a pair of iterators instead of a container, but the two big ones here are that
the
computeStuff
function can take a range from any type of container, not just astd::vector
, andthe range just has to contain objects that are convertible to the type that you want to use (e.g.
boost::shared_ptr<Parent>
), it doesn't actually have to contain objects of that specific type.