我可以在不查看每个元素的情况下将std :: vector <Animal*>转换为std :: vector <Dog*>吗?

Bea*_*sen 8 c++ templates casting vector

我有一个基类,有几个类扩展它.我有一些通用的库实用程序,它们创建一个包含指向基类的指针的向量,以便任何子类都可以工作.如何将向量的所有元素强制转换为特定的子类?

// 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);
}
Run Code Online (Sandbox Code Playgroud)

我天真的解决方案看起来像这样:

// 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*sky 11

你可以用std::transform.它仍然在for()内部使用,但你会得到两个字符串的实现:

#include <vector>
#include <algorithm>
using namespace std;

struct Animal { virtual ~Animal() {} };
struct Dog : Animal { virtual ~Dog() {} };

template<typename Target>
struct Animal2Target { Target* operator ()( Animal* value ) const { return dynamic_cast<Target*>(value); } };

void myDogCallback(vector<Animal*> &animals) {
{
    vector<Dog*> dogs;
    transform( animals.begin(), animals.end(), dogs.begin(), Animal2Target<Dog>() );
}
Run Code Online (Sandbox Code Playgroud)

  • 这仍然是"看每个元素",流程只是以不同的方式排列. (2认同)

pax*_*977 0

当动物向量包含其他动物专业化时,您编写的代码会将一堆空指针放入您的狗向量中。

vector<Dog*> dogs;
vector<Animal*>::iterator iter;
Dog* dog;

for( iter = animals.begin(); iter != animals.end(); ++iter )
{
  dog = dynamic_cast<Dog*>(*iter);
  if( dog )
  {
    dogs.push_back( dog );
  }
}
Run Code Online (Sandbox Code Playgroud)