Re: Inheritance and offsetof
Francesco S. Carta wrote:
If you already have an instance of your type, you are right, but
otherwise you have to make your own pseudo-instance. And that is exactly
the way the macros offsetof and my structoffsetof work with all that casts.
Furthermore when dealing with an instance I would prefer to cast to
char*: (char*)&b.m3 - (char*)&(A&)b
Thanks for your explanation, now it's clearer.
I just saw a bug in the example, which may have caused confusion.
It should have been:
void foo(A*);
int main()
{ B b;
b.m1 = offsetof(B, m3) - structoffsetof(B, A);
foo(&b);
return 0;
}
I still think you could avoid those macros, also you could avoid C-
style casts.
I think there is no way of implementing things like offsetof without a
C-style cast.
I'm just saying this because I've been told several times to never use
C-style casts,
This works unless you have to deal with void* or something like offsetof.
and also to avoid macros whenever possible - and for
such cases, I've been told to make macros all-caps.
Have you considered making some template functions to replace those
macros?
Yes, just after my last post. Unfortunately while it is trivial to write
a template for structoffsetof I see no way to implement offsetof via a
template. It is because you cannot reasonably pass the element selector
as template argument without using lambda expressions. The latter would
require a very modern compiler because of the return type deduction.
Furthermore the compiler might no longer check that it is a compile time
constant.
As I said, I have no answer for your specific issue, I'm just
bordering along, sorry.
I think I will find a way to avoid this annoying warnings, again using
macros.
But I still wonder why offsetof should be invalid for inherited types.
The result of offsetof is not portable anyway because of alignment and
type size issues. But within a given plattform the result should be
stable as long as you do not deal with virtual base classes.
Marcel