How about storing the data member as array and access them by names?
struct vec {
float p[3];
float& x() { return p[0]; }
float& y() { return p[1]; }
float& z() { return p[2]; }
float& operator[](std::size_t i)
{
assert(i < 3);
return p[i];
}
};
EDIT: For the original approach, if x, y and z are all the member variables you have, then the struct will always be the size of 3 floats, so static_assert
can be used for checking that operator[]
will access within bounded size.
See also: C++ struct member memory allocation
EDIT 2: Like Brian said in another answer, (&x)[i]
itself is undefined behaviors in the standard. However, given that the 3 floats are the only data members, the code in this context should be safe.
To be pedantic on syntax correctness:
struct vec {
float x, y, z;
float* const p = &x;
float& operator[](std::size_t i) {
assert(i < 3);
return p[i];
}
};
Although this will increase each vec by the size of a pointer.