Pra*_*rav 3 c++ templates offset
这是代码片段
#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
}
Run Code Online (Sandbox Code Playgroud)
我们无法创建指向引用的指针,因此该函数Offsetof不起作用z.
有没有办法为非POD取得参考数据成员的偏移量?