0
struct S1 {
    int a;
};

struct S2 {
    int b;
    S1 s;
};

int S2::*ptrB = &S2::b; // pointer to data member 'b'
int S2::*ptrA = ?       // pointer to data member 'a'

Is it possible to have member pointer to a member variable?

EDIT:

Many people asked why I need this. I have many duplicated code lines like this:

object.get("struct1.struct2.var1", &record.struct2.var1);
object.get("struct1.struct3.var1", &record.struct3.var1);

object.get("struct1.struct2.var1", &record2.struct2.var1);
object.get("struct1.struct3.var1", &record2.struct3.var1);

My goal is to create list of string and member pointers and then iterate over this list.

  • 2
    I wonder why somebody would want that – Slava Mar 09 '17 at 20:05
  • 2
    Just curious, what exactly is your use case for this? – Borgleader Mar 09 '17 at 20:06
  • @Slava answered in edit – Krzysztof Sakowski Mar 09 '17 at 20:20
  • The answer is no to the code you put, since in your struct S2, s is not a pointer of an S1 struct, there is no way you can track it outside the scope of S2. However the following code will work: struct S1 { int a; }; struct S2 { int b; S1 *s; }; ...//some code to create an S2 called S2_instance that contains a valid s1 pointer (S2_instance->s)->a this will give back the a you store in your S1 – n4feng Mar 09 '17 at 20:21

0 Answers0