给定一个聚合的struct/class,其中每个成员变量都具有相同的数据类型:

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,我可以避免分配。

最佳答案

强制转换它不需要按标准工作。

但是,您可以通过使用静态断言来确保代码安全,如果违反假设,这些断言将阻止其编译:

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);

10-08 14:38