取参考成员的偏移量(非POD) [英] Taking offset of a reference member (non PODs)
本文介绍了取参考成员的偏移量(非POD)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是代码段
#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
.
We cannot create pointer to reference so the function Offsetof
won't work for z
.
对于非POD,有什么方法可以使参考数据成员偏移吗?
Is there any way to take offset of a reference data member for non PODs?
推荐答案
否.引用不是对象,它们不存在或没有地址或偏移量.指向成员引用的指针是非法的.
No. References are not objects, and they do not exist or have addresses or offsets. A pointer to a member reference is illegal.
这篇关于取参考成员的偏移量(非POD)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文