Is it possible to distinguish an STL container with a base type from a derived type?

Is it possible to distinguish an STL container from a base type to a derived one? For example, I have two vectors. The first is in the type of the base class, the second is in the type of the Derive class.

class Base
{
// Code
};

class Derive : public Base
{
// Code
};

Using

    vector<Base*>*  vec_base = new vector<Base*>;

    // Add some Derive type data to vec_base

    vector<Derive*>* vec_derive = (vector<Derive*>*)(vec_base);

    // Using elements as Derive pointers. Works fine. 

This is normal? (It works great, but I wanted to get some comments about it). Many thanks.

EDIT: update according to answers.

Say, if I use this vector carefully and don’t use it with multiple inheritance and don’t insert objects other than Derive type, is this normal? (I think it is not)

And thanks for the answers.

+5
source share
5 answers

, c. " " .

, :

#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

class Base
{
// Code
virtual ~Base();
};

class Derrive : public Base
{
// Code
};

Derrive *convert(Base * in) {
   // assert here?
   return dynamic_cast<Derrive*>(in);
}

int main() {
    vector<Base*>*  vec_base = new vector<Base*>;

    // Add some Derrive type data to vec_base

    vector<Derrive*>* vec_derrive = new vector<Derrive*>;

    transform(vec_base->begin(), vec_base->end(), back_insert_iterator<vector<Derrive*> >(*vec_derrive), convert);
}
+8

c-style cast, reinterpret_cast, " x y , ". , . , , .

:

for (unsigned int i=0; i < vec_base->length(); i++)
{
  Derrive* d = dynamic_cast<Derrive*> (vec_base[i]);
  if (d ) {
     // this element is a Derrive instance, so we can treat it like one here
  }
  // else, skip it, log an error, throw an exception, whatever,
  // this element in the vector is not of type Derrive
}
+2

. T ( std::vector, C- undefined.

, , , .

, , . , .

+1

. .

, Derrive2, Base. STL, Derrive.

0

- std:: transform.

std:: list, T = Base * T = Derived * ( ), , . , :

vector<Derived*> vector2 = *( reinterpret_cast< vector<Derived*>* >(&vector1) );

: , , std:: transform. , STD++ , GCC, , .. , "list < Base * > list < Derivated * > " .

0

All Articles