我见过的最常见的解决方法是通过重载类型的数组运算符来解决。这种方法相当特定于您发布的示例,但在其他情况下似乎没有其他选择的情况下,可以使用类似的方法。
struct Mat {
F32
_11, _12, _13, _14,
_21, _22, _23, _24,
_31, _32, _33, _34,
_41, _42, _43, _44;
f32& operator[](uint32 ndx) {
return *reinterpret_cast<F32*>(&((&_11)[ndx]));
}
const F32& operator[](uint32 ndx) const {
return *reinterpret_cast<const F32*>(&((&_11)[ndx]));
}
};
但是,如果有矩阵,通常也会有向量,这可以通过在向量类中定义数组运算符来利用。与上面定义的数组运算符不同,它不返回矩阵数组运算符中的F32引用,而是返回一个向量引用。以下是一个示例:
struct vector4{
F32 x,y,z,w;
f32& operator[](uint32 ndx) {
return *reinterpret_cast<F32*>(&((&x)[ndx]));
}
const F32& operator[](uint32 ndx) const {
return *reinterpret_cast<const F32*>(&((&x)[ndx]));
}
};
struct matrix4 {
F32
_11, _12, _13, _14,
_21, _22, _23, _24,
_31, _32, _33, _34,
_41, _42, _43, _44;
vector4& operator[](uint32 ndx) { return *reinterpret_cast<vector4*>(&((&_11)[ndx * 4])); }
const vector4& operator[](uint32 ndx) const { return *reinterpret_cast<const vector4*>(&((&_11)[ndx * 4])); }
};
现在编程可以更自然地书写,而且仍然高效,例如:
F32 m00 = mymat4[0][0];
或者:
vector4 col0 = mymat4[0]
这种方法最大的缺点是矩阵现在必须以[col][row]的索引方式进行访问。可以通过向类中添加operator()来解决这个问题...但那是另一个故事了。