Is it really intended to point to a pointer to a structure pointer to an array?

Given an aggregate structure / class in which each member variable has the same data type:

struct MatrixStack { Matrix4x4 translation { ... }; Matrix4x4 rotation { ... }; Matrix4x4 projection { ... }; } matrixStack; 

How valid is its transfer to the array of its members? eg.

 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 do this because in most cases, for clarity, I need access to the member name, while in some other cases I need to pass the array to some other API. Using reinterpret_cast, I can avoid highlighting.

+6
source share
1 answer

The order is not required to work according to the standard.

However, you can make your code safe by using static statements that will prevent it from compiling if 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); 
+3
source

All Articles