【发布时间】:2010-11-13 14:55:11
【问题描述】:
我有一个基类,其中有几个扩展它的类。我有一些通用库实用程序,它们创建一个包含指向基类的指针的向量,以便任何子类都可以工作。如何将向量的所有元素转换为特定的子类?
// A method is called that assumes that a vector containing
// Dogs casted to Animal is passed.
void myDogCallback(vector<Animal*> &animals) {
// I want to cast all of the elements of animals to
// be dogs.
vector<Dog*> dogs = castAsDogs(animals);
}
我的幼稚解决方案看起来像这样:
// A method is called that assumes that a vector containing
// Dogs casted to Animal is passed.
void myDogCallback(vector<Animal*> &animals) {
// I want to cast all of the elements of animals to
// be dogs.
vector<Dog*> dogs;
vector<Animal*>::iterator iter;
for ( iter = animals.begin(); iter != animals.end(); ++iter ) {
dogs.push_back(dynamic_cast<Dog*>(*iter));
}
}
【问题讨论】:
-
这不是骗人的——注意他不是从
vector<Derived*>复制到vector<Base*>,而是反过来! -
我猜他正在寻找一种自动/隐含的沮丧!
-
感谢您的反馈。 :) 不知道怎么问,是的,很难知道要搜索什么!
标签: c++ templates vector casting