If o is an object and m is a member of the object, and you know the adress of m, can you then tell the adress of o?
If o is an object and m is a member of the object, and you know the adress of m, can you then tell the adress of o?
Come on, you can do it! b( ~_')
you can use the offsetof macro, but it won't work for members that are references.
Code:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 0; }
Nor will it work if the member is a function, of course.
Furthermore, offsetof may only be used for PODs, just like the necessary pointer casts are valid only for PODs.
POD (Plain Ol' Data) types are, succinctly put, those that can be written in C. (That's not quite accurate, but sufficiently so.)
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
It CAN be done, but as explained, there are MANY restrictions, the most obvious covered above.
Linux (and related) have a macro to get a base-pointer from a member of a function, like this:
--Code:#define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );})
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
The most portable way to do it would be if you had a pointer to a member function -- in which case you could just return this -- or make m itself have a member pointing to o. Or just have a pointer to o in the first place.
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.
Basically, in any situation where you can assume that the pointer you actually does point to a member of a struct, and you find you need a pointer to that struct but don't have one, you're facing a design error. You should have provided a pointer to the struct to the component in question in the first place.
In most situations, you can't assume that you've got a member.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law