与成员指针的偏移量,没有临时实例 [英] Offset from member pointer without temporary instance
问题描述
当我为标准版式成员变量提供变量时,我想获取它的偏移量.我不能使用 offsetof
,因为我有一个指针而不是一个名称.我目前使用的代码看起来像这样,我想知道是否存在一种符合标准的方法来消除 dummy
变量.
I would like to get the offset of a standard layout member variable when provided with a poiner to that variable. I cannot use offsetof
since I have a pointer and not a name. The current code I have looks something like this, and I am wondering if there is a standards compliant way to get rid of the dummy
variable.
template<class T>
struct {
ptrdiff_t get_offset( int (T::*mem) )
{
T dummy;
return reinterpret_cast<char*>(&(dummy.*mem))
- reinterpret_cast<char*>(&dummy);
}
};
此函数只能与 int
成员变量点一起调用(这是有意的).
This function should only be callable with int
member variable points (this is intentional).
我敢肯定,编译器实际上并没有创建 dummy
变量,但是如果我能摆脱它的话,它仍然很不错.我不能使用null指针,因为未定义对null的取消引用(尽管它可能适用于所有常见的编译器).C ++ 03解决方案会很好,或者C ++ 11解决方案也很有趣(但我现在无法使用).
I am quite certain that the compiler doesn't actually create the dummy
variable but it'd still be nice if I could get rid of it. I can't use a null pointer since dereferencing null is not defined (though it probably works on all common compilers). A C++03 solution would be good, or a C++11 solution is also of interest (but not usable by me now).
注意:我已经知道这只是符合标准的标准,而T是标准的布局类型.
推荐答案
怎么样:
template<class T>
struct {
ptrdiff_t get_offset( int (T::*mem) )
{
union {
int used;
T unused;
} dummy;
return reinterpret_cast<char*>(&(dummy.unused.*mem))
- reinterpret_cast<char*>(&dummy.unused);
}
};
工会成员的地址不取决于所构建的工会成员.在C ++ 03中已经可以使用,但仅适用于POD.
The address of a union member doesn't depend on the union member being constructed. Works already in C++03, but then only for PODs.
这篇关于与成员指针的偏移量,没有临时实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!