Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Offset of pointer to member

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

like image 634
0xbadf00d Avatar asked Apr 11 '11 05:04

0xbadf00d


2 Answers

@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)
    );
}
like image 103
0xbadf00d Avatar answered Sep 22 '22 13:09

0xbadf00d


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

like image 39
Michael J Avatar answered Sep 20 '22 13:09

Michael J