Yes you can, although you cannot declare it as a member of an array. You can use the link:
struct s { int ( & extra_arr )[]; s() : extra_arr( reinterpret_cast< int (&)[] >( this[1] ) {} };
In practice, this will use the value of the storage pointer, although theoretically this is not necessary. This class is not a POD, due to the difference between theory and practice.
You can alternately put reinterpret_cast in a non-statistical member function:
struct s { int ( & get_extra() )[] { return reinterpret_cast< int (&)[] >( this[1] ); } int const ( & get_extra() const )[] { return reinterpret_cast< int const (&)[] >( this[1] ); } };
Now access requires the syntax of the function call (the insert eliminates the difference in machine codes, except for the debug build), but there is no lost storage, and the object will be a POD prohibiting any other exception to the POD rules.
With a little customization of ABI, such as #pragma pack , you can get full compatibility with C. Often this setting is necessary for serialization applications.
Support for const-correctness is also supported, while the previous solution allows you to modify the const object (since it does not know that the array is part of the same object).
A wrapper can be generalized to a CRTP base class (which in C ++ 11 even still allows a derived class to be a POD) or a preprocessor macro that expands to define either C ++ access or a C element of flexibility.
Note that none of these solutions do anything except the original C. Special member functions will not copy the flexible array, and the class cannot support a function parameter or subobject.
source share