more headachy c++ gubbish.
Jul. 17th, 2008 05:30 pmIn C you can totally do this.
typedef struct { ... } S;
typedef struct { ...; S s; ... } T;
/* ESS assumed to be contained in a T. */
T * TfromS(S * ess) {
return (T *)(((char *)ess) - offsetof(T, s));
}
But in C++, offsetof is not defined when its first argument is a “non-POD type” (approximately, “a type you couldn't have declared in C.”) The replacement for offsetof is the “pointer to member.”
But you can't do the above with a pointer to member.
So how the Belgium do you do it?
no subject
Date: 2008-07-18 01:55 am (UTC)no subject
Date: 2008-07-18 04:37 am (UTC)no subject
Date: 2008-07-18 05:16 am (UTC)good compiler, no donut
Date: 2008-07-18 08:52 am (UTC)Then reality comes in.
Anyway, a google search earlier came up with this gem:
http://quantumreference.blogspot.com/2008/03/making-c-macro-offsetof-work-with-c.html
I haven't tried it myself, but it seems that a sufficient number of
reinterpret_casts and possible a static dummy instance should also work.(Or, if every S really is in a T, then just teach S about its containing T. But in this case, I'm presuming that you're mostly trying to port over an existing code base, yes?)
Good luck.
Re: good compiler, no donut
Date: 2008-07-18 03:38 pm (UTC)Re: good compiler, no donut
Date: 2008-07-18 07:11 pm (UTC)Yeah, but since C++ is only looking at a single function whose argument is an S, it can't know that.
The most straightforward way would be to add a pointer-to-T to the structure S. Downside is that it increases the size of S.
This thread is interesting: http://coding.derkeiler.com/Archive/C_CPP/comp.lang.cpp/2005-01/1105.html
Other random thoughts:
* You can't do it as a compile-time constant, due to virtual inheritance (I think that's the problem). You would have to traverse vtables at runtime.
* Try putting functions that need to do this in a C file with "C" linkage? If everything involved is "mostly a POD", then that might work well enough.
Really, though, it sounds like C++ might not be the right fit for this, if you're not free to use it properly (and "no-rtti" is often an indicator of exactly that).
Good luck.
no subject
Date: 2008-07-18 08:14 pm (UTC)no subject
Date: 2008-07-19 02:15 am (UTC)Of course, I'm guessing by now you've come up with some other approach, which might be for the best anyway...