Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

template<class T, typename U> ptrdiff_t foo(T U::* m)
{
    // return offset
}

How I can get the offset of the field 'm' in this context? I would prefer to use am compile-time expression.

Thanks in advance for any help. Best regards

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
978 views
Welcome To Ask or Share your Answers For Others

1 Answer

@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)
    );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...