I’m using the Chipmunk physics engine for my C++ project.
Chipmunk has it’s own vector, cpVect, which is nothing but a struct { double x, y; };
However I have my own operator overloaded Vector class in my project – and I’d like to use it just as a cpVect and vice-versa, without any conversions
(my class Vector‘s only data fields are double x, y as well)
Currently I use this for implicit conversions (for argument passing, setting a Vector variable to a cpVect, etc.)
inline operator cpVect() { return cpv( x, y ); };
inline Vector( cpVect v ) : x( v.x ), y( v.y ) {}
This works for most things, but has a few problems – for example it isn’t compatible for using arrays of the type Vector with cpVect arrays.
For that I currently have to do this:
Vector arrayA[123];
cpVect* arrayB = (cpVect*) arrayA;
- Is it possible by some way to use my Vector as cpVect and vice-versa? Data is identical with both structures, mine only has additional methods.
So if I understand you, you have this:
…and you want pretened that a
Foois actually aBar, right?You can’t — not without evoking Undefined Behavior. No matter what you try, you will fall in to the great UB black hole.
my_union.fooand read frommy_union.barreinterpret_castyou’ll evoke UB when to try to use the casted pointerThe problem is this: Even though
FooandBarlook the same, they are not the same. As far as C++ is concerned, they are completely different types, totally unrelated to each other. This is a Good Thing, but it can also throw up some barriers that can seem to be artificial and arbitrary.So, in order to do this without evoking UB, you need to convert. You could make this nearly automatic, by simply adding a couple facilities to
Bar(which I presume to be the one you wrote, not the one from the library):Which will let you go from
FootoBarand back again with little or no code. Plus the compiler will optimize a lot of this away in release builds.