c++ - Cast pointer to fixed-size array in return statement -
the simplest way ask question code:
struct point { int x; int y; int z; int* as_pointer() { return &x; } // works int (&as_array_ref())[3] { return &x; } // not work };
as_pointer
compiles, as_array_ref
not. cast seems in order can't figure out appropriate syntax. ideas?
i find array types easier deal with typedef:
typedef int ints[3];
then as_array_ref
must written &as_array_ref() == &x
.
the following syntaxes possible:
plain c-style cast
int*
ints*
:ints& as_array_ref() { return *( (ints*)(&x) ); }
c++ style
reinterpret_cast
(suggested @mike seymour - see answer). considered better practice in c++:ints& as_array_ref() { return *reinterpret_cast<ints*>(&x); }
cast
int&
ints&
shorter (for me) less intuitive:ints& as_array_ref() { return reinterpret_cast<ints&>(x); }