取参考成员(非 POD)的偏移量

Taking offset of a reference member (non PODs)

本文关键字:偏移量 POD 参考 成员      更新时间:2023-10-16

这是代码片段

#include <iostream>
struct Z
{
   Z():x(0),y(0),z(x){}
   ~Z(){}
   int x;
   int y;
   int &z; // Reference member
};
template <typename Type, typename C, typename M>
size_t Offsetof (M C::* ptr_to_member)
{
  Type type;
  return reinterpret_cast<char*> (&(type.*ptr_to_member)) - reinterpret_cast<char*> (&type);
}
int main()
{
   std::cout << Offsetof<Z>(&Z::x); // works
   std::cout << Offsetof<Z>(&Z::y); // works 
   std::cout << Offsetof<Z>(&Z::z); // doesn't work
}

我们无法创建指向引用的指针,因此函数Offsetof不适用于z

有没有办法为非 POD 获取参考数据成员的偏移量?

No.引用不是对象,它们不存在,也没有地址或偏移量。指向成员引用的指针是非法的。