取参考成员(非 POD)的偏移量
Taking offset of a reference member (non PODs)
这是代码片段
#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.引用不是对象,它们不存在,也没有地址或偏移量。指向成员引用的指针是非法的。
相关文章:
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 通过指针偏移量访问结构变量值
- 以线程安全的方式转换 C/C++ 中时区名称字符串的时区偏移量
- librdkafka:rd_kafka_assignment 返回分配分区的偏移量 -1001
- 是否通过向封闭对象的地址添加字节偏移量来访问子对象
- 向指针地址添加 20 个字节偏移量
- glMapBufferRange(..) 中的偏移量关系和 glDrawArraysInstanced(..) 中的第一
- 是否有与 C# Structs/StructLayout 等效的功能,C++中的字段偏移量?
- 我的 sumASCII 函数中的此偏移量是多少?
- boost::序列化中的派生类偏移量计算.有效吗?
- RedisGraph 语法错误在偏移量 8 靠近"创建"
- 胎面偏移量的时间复杂度?
- 如何从 c++ 中的给定标准输入中获取每个字符的偏移量?
- 编译器在构造函数中计算的成员偏移量不正确
- 使用基地址和偏移量获取变量的地址
- c++ 读取进程内存基址 + 偏移量不起作用
- 通过其在 C 中的偏移量调用函数
- ld:无效的字符串偏移量...对于".strtab"部分
- 取参考成员(非 POD)的偏移量
- POD声明中成员变量的引用偏移量