假设有一个聚合结构体/类,其中每个成员变量都是相同的数据类型:
struct MatrixStack {
Matrix4x4 translation { ... };
Matrix4x4 rotation { ... };
Matrix4x4 projection { ... };
} matrixStack;
将其转换为其成员数组有多有效?例如:
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());
我这样做是因为在大多数情况下,我需要使用命名成员访问来提高代码的清晰度,而在其他一些情况下,我需要将数组传递给其他API。通过使用reinterpret_cast,我可以避免分配内存。