Pointer to member-of-member???

L

LR

Steve said:
I can't for the life of me see how to do pointer-to-member when the
member is actually part of an embedded structure.

That is, if I have:

struct S1 { int a; };
struct S2 { S1 s; int b; };

how can I get a pointer to the a in an S2?

I don't think that can be done with a single variable.

Obviously I can point at the b with

int S2:*p = &S2::b;

But the seemingly obvious syntax

int S2::*p = &S2::s.a;

doesn't work - because S2::s.a is not a /qualified-id/ - and neither
does anything else I can think of.

After all, if I have an S2 structure, there's absolutely no difference
from the compiler's POV between s2.s.a and s2.b, so why should I not be
able to have a construct s2.*p equivalent to the former case?

I think for the same reason that you can't use a pointer to a pointer to
an int to get the int. You have to get the thing that the pointer to a
pointer points to first, then you can get the int.

At the moment, the only thing I have found is a rather yucky workaround
with offsetof() macros and lots of casts. That is,

size_t offset = offsetof (S2, s.a);

*(int *) ((char *) &s2 + offset) = 123;

Ugh :-(((

Any better suggestions gratefully received!

I don't know that it's better, and it's not really an answer to your
question but more in the way of a work around.


struct S1 { int a; };
struct S2 {
private:
static int S1::*px_;
public:
S1 s;
int b;

static void s(int S1::*px) { px_ = px; }
int &px() { return s.*px_; }
};

int S1::*S2::px_;

You can use it like this:

// better make sure it's initialized before you use it.
S2::s(&S1::a);

S2 w;
w.px() = 14;

There may be some details to be worked out and there's probably a better
way to do it.

LR
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,600
Members
45,179
Latest member
pkhumanis73
Top