The simplest way to ask this question is with some code:
struct Point
{
int x;
int y;
int z;
int* as_pointer() { return &x; } // works
int (&as_array_ref())[3] { return &x; } // does not work
};
as_pointer
compiles, as_array_ref
does not. A cast seems to be in order but I can't figure out the appropriate syntax. Any ideas?
I find that array types are easier to deal with with a typedef:
typedef int ints[3];
Then your as_array_ref
must be written so that &as_array_ref() == &x
.
The following syntaxes are possible:
plain C-style cast from int*
to ints*
:
ints& as_array_ref() { return *( (ints*)(&x) ); }
C++ style reinterpret_cast
(suggested by @Mike Seymour - see also his answer). It is often considered a better practice in C++:
ints& as_array_ref() { return *reinterpret_cast<ints*>(&x); }
Cast from int&
to ints&
which is slightly shorter but (for me) less intuitive:
ints& as_array_ref() { return reinterpret_cast<ints&>(x); }
The cast you need to reinterpret a reference to a variable as a reference to an array is:
reinterpret_cast<int(&)[3]>(x);
Be aware that using this gives undefined behaviour; it will probably work on any sensible implementation, but there's no guarantee that there won't be padding between the members of the class, while arrays are not padded.
I think that what you're trying to do would be easier (and clearer/cleaner) with an union.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With