这是来自英特尔 Embree code 中的 vec3fa.h 。

struct __aligned(16) Vec3fa
{
typedef float Scalar;
enum { N = 3 };
union {
  __m128 m128;
  struct { float x,y,z; union { int a; float w; }; };
};

// other stuff in struct

};

外联在做什么?内心的结合对我来说更加神秘。
代码中从不引用 a 和 w 变量。

看起来这提供了一种使用适当别名读取和写入 m128、x、y 和 z 的方便和干净的方式。它是如何工作的?

int是怎么参与进来的??

最佳答案

它们是 anonymous unions (和一个结构体)。他们所做的是就地定义结构体或 union 体的匿名实例,用于避免访问成员时出现困惑。上面的代码与这个布局兼容:

struct __aligned(16) Vec3fa
{
  typedef float Scalar;
  enum { N = 3 };
  union {
    __m128 m128;
    struct { float x,y,z; union { int a; float w; } u2; } s;
  } u1;
  // other stuff in struct
};

但现在成员(member)访问更加复杂:
Vec3fa v;      // offset from struct start ((char*)&member - (char*)&v):
v.u1.m128;     // 0
v.u1.s.x;      // 0
v.u1.s.y;      // 4
v.u1.s.z;      // 8
v.u1.s.u2.w;  // 12
v.u1.s.u2.a;  // 12

而不是库变体:
Vec3fa v;      // offset from struct start ((char*)&member - (char*)&v):
v.m128;        // 0
v.x;           // 0
v.y;           // 4
v.z;           // 8
v.w;           // 12
v.a;           // 12

关于c++ - 英特尔 Embree 的这个 union 有什么作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22275285/

10-14 23:58