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:

  1. plain c-style cast int* ints*:

    ints& as_array_ref() { return *( (ints*)(&x) ); }

  2. c++ style reinterpret_cast (suggested @mike seymour - see answer). considered better practice in c++:

    ints& as_array_ref() { return *reinterpret_cast<ints*>(&x); }

  3. cast int& ints& shorter (for me) less intuitive:

    ints& as_array_ref() { return reinterpret_cast<ints&>(x); }


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -