关于C#:获取参考成员的偏移量(非POD)

Taking offset of a reference member (non PODs)

这是代码段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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
}

我们无法创建引用指针,因此功能Offsetofz不起作用。

对于非POD,有什么方法可以使参考数据成员偏移吗?


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