Given an aggregate struct/class in which every member variable is of the same data type:
struct MatrixStack {
Matrix4x4 translation { ... };
Matrix4x4 rotation { ... };
Matrix4x4 projection { ... };
} matrixStack;
How valid is it to cast it to an array of its members? e.g.
const Matrix4x4 *ptr = reinterpret_cast<const Matrix4x4*>(&matrixStack);
assert(ptr == &matrixStack.translation);
assert(ptr + 1 == &matrixStack.rotation);
assert(ptr + 2 == &matrixStack.projection);
auto squashed = std::accumulate(ptr, ptr + 3, identity(), multiply());
I am doing this because in most cases I need named member access for clarity, whereas in some other cases I need to pass the an array into some other API. By using reinterpret_cast, I can avoid allocation.
The cast it not required to work by the standard.
However, you can make your code safe by using static asserts that will prevent it from compiling if the assumptions are violated:
static_assert(sizeof(MatrixStack) == sizeof(Matrix4x4[3]), "Size mismatch.");
static_assert(alignof(MatrixStack) == alignof(Matrix4x4[3]), "Alignment mismatch.");
// ...
const Matrix4x4* ptr = &matrixStack.translation;
// or
auto &array = reinterpret_cast<const Matrix4x4(&)[3]>(matrixStack.translation);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With