C++ reinterpret cast?

2019-09-06 03:51发布

问题:

I would like to cast one object of the class PointsList to another object Points3DList (and vice versa) where:

template <class T>
class PointsList
{
    protected:
            std::vector <Point <T> *> points;  //Only illustration, not possible with templaes
};

and

 template <class T>
class Points3DList
{
    protected:
            std::vector <Point3D<T> *> points;  //Only illustration, not possible with templaes
};

Between Point and Point3D there is no relationship (inheritance nor composition)...

template <class T>
class Point
{
    protected:

            T x;
            T y;

    public:
            Point( const T &x_, const T &y_ ) : x ( x_ ), y ( y_ ) {}
            inline T getX() const {return x;}
            inline T getY() const {return y;}
            inline void setX ( const T &x_ ) {x = x_;}
            inline void setY ( const T &y_ ) {y = y_;}
            ....
};

template <class T>
class Point3D
{
    protected:

            T x;
            T y;
            T z;
};

What do you think about conversion

Points3DList <T> *pl3D = new Points3DList <T> ();
...
PointsList <T> *pl = reinterpret_cast < PointList <T> * > ( pl3D );

where pl3D represents pointer to Points3DList object.. Can reinterpret_cast be used in this case or it is better to create a conversion function? Data model in this case can not be changed...

回答1:

The behaviour here will be completely undefined. Don't do it!



回答2:

You must write your own cast function (constructor or friend function).

Something like:

template <class T>
class PointsList
{
    PointsList(Points3DList& p3d) : x(p3d->x), y(p3d->y) {};
... 

And use:

PointsList <T> *pl = new PointList( pl3D );


回答3:

PointsList <T> *pl = reinterpret_cast < PointList <T> * > ( pl3D );

This doesn't make sense. Terribly Wrong. You'll get only garbage out of such cast!

How do you even expect reinterpret_cast to interpret Point and Point3D to make the casting succeed?