Taking offset of a reference member (non PODs)

霸气de小男生 提交于 2020-01-14 22:54:37

问题


Here is the code snippet

#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
}

We cannot create pointer to reference so the function Offsetof won't work for z.

Is there any way to take offset of a reference data member for non PODs?


回答1:


No. References are not objects, and they do not exist or have addresses or offsets. A pointer to a member reference is illegal.



来源:https://stackoverflow.com/questions/13562766/taking-offset-of-a-reference-member-non-pods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!