Offset of pointer to member

[亡魂溺海] 提交于 2019-11-29 14:16:20

Sounds like you're looking for the offsetof() macro.

@Michael J

Thanks for your answer. This wasn't exactly what I was looking for, but it gives me the inspiration to doing that:

template<class T, typename U>
std::ptrdiff_t member_offset(U T::* member)
{
    return reinterpret_cast<std::ptrdiff_t>(
        &(reinterpret_cast<T const volatile*>(NULL)->*member)
    );
}

The simple answer is that you can't. If the type U is a POD, you can use the macro offsetof, but formally, it's undefined behavior if the type isn't a POD: depending on the compiler, you'll get a compile time error, or simply wrong results some of the time. And you can't use it on a pointer to member. You have to invoke it with the name of the class, and the name of the member.

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