You can never be sure that this will work
There is no guarantee of contiguity of subsequent members, even if this will frequently work perfectly in practice thanks to usual float alignment properties and permissive pointer arithmetic.
This is laid down in the following clause of the C++ standard:
[class.mem]/18: Non-static
data-members (...) with the same access control are allocated so that
later members have higher addresses within the class object.
Implementation alignment requirements might cause two adjacent members
not to be allocated after each other.
There is no way to make this legal using static_assert
nor alignas
constraints. All you can do is to prevent the compilation, when the elements are not contiguous, using the property that the address of each object is unique:
static_assert (&y==&x+1 && &z==&y+1, "PADDING in vector");
But you can reimplement the operator to make it standard compliant
A safe alternative, would be to reimplement operator[]
to get rid of the contiguity requirement for the three members:
struct vec {
float x,y,z;
float& operator[](size_t i)
{
assert(i<3);
if (i==0) // optimizing compiler will make this as efficient as your original code
return x;
else if (i==1)
return y;
else return z;
}
};
Note that an optimizing compiler will generate very similar code for both the reimplementation and for your original version (see an example here). So rather choose the compliant version.
float [3]
member, possibly with accessors likex()
,y()
andz()
– Crystlecsget<i>
function that select at compile time the member. – Dziggetaiget<i>(vec)
function. – Dziggetai