C++ How to set a pointer of type std::vector<Derived*> to object of type std::vector<Base*>

StackOverflow https://stackoverflow.com/questions/11820490

  •  24-06-2021
  •  | 
  •  

Domanda

The Background:

I'm building a physics engine in C++ that computes the gravitational evolution of an n-body system in Cartesian space and then translates that into any of a predefined set of coordinate systems. Eventually the goal is the make the starting coordinate system arbitrary (calculate in coordinate system 'n' instead of only Cartesian), but that is a distant goal.

The Problem:

Because the coordinate system is supposed to be interchangeable, I have made the Cartesian coordinate system extend a base coordinate system:

class CoordMember {
}

class CoordState {
   public:
      /* methods to operate on members */

   protected:
      std::vector<CoordMember*> members;
}

class Particle : public CoordMember {
}

class CartState : public CoordState {
}

The error arises when trying to create a pointer of type std::vector<Particle*> which points to the members object of type std::vector<CoordMember*>:

CartState* state = new CartState(/* initialization vars */);
std::vector<Particle*>* parts = static_cast< std::vector<Particle*>* >(&state->members);

Compiler errors are:

error: static_cast from 'std::vector<CoordMember *> *' to 'std::vector<Particle *> *' is not allowed
error: no viable overloaded '='

I know for a fact at this point that the data in state->members are all of type Particle*. What I don't know is what has to be done to make this cast possible. Any ideas?

tl;dr:

std::vector<Derived*>* ptr = static_cast< std::vector<Base*>* >(&object);
static_cast from 'std::vector<Derived*>*' to 'std::vector<Base*>*' is not allowed
È stato utile?

Soluzione

The cast doesn't work because the vectors are completely unrelated. You'll have to cast each individual object in the vector.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top