给定一个聚合结构/类,其中每个成员变量具有相同的数据类型:
struct MatrixStack {
Matrix4x4 translation { ... };
Matrix4x4 rotation { ... };
Matrix4x4 projection { ... };
} matrixStack;
Run Code Online (Sandbox Code Playgroud)
将它投射到其成员数组的有效性如何?例如
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());
Run Code Online (Sandbox Code Playgroud)
我这样做是因为在大多数情况下我需要命名成员访问以获得清晰度,而在其他一些情况下我需要将一个数组传递给其他API.通过使用reinterpret_cast,我可以避免分配.