Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointer to member of member

//#define NOT_WORKS
#define HOW(X) 0

struct A {

};

struct B {
    A a;
};

struct C {
    B b;
};

int main(int argc, char **argv) {
    A B::*ba = &B::a;       // ba is a pointer to B::a member
    B C::*cb = &C::b;       // cb is a pointer to C::b member

#ifdef NOT_WORKS

    { A C::*ca = &C::b::a; }    // error: Symbol a could not be resolved / error: ‘C::b’ is not a class or namespace
    { A C::*ca = cb + ba; }     // error: invalid operands of types ‘B C::*’ and ‘A B::*’ to binary ‘operator+’

    A C::*ca = HOW(???);        // is possible to reach C::b::a by a member pointer?

#endif

    C cptr;
    A aptr = cptr.*cb.*ba;  // is pointer inference chaining the only solution?

    return 0;
} 

If the inference chaining of member pointers is the only solution to reach a inner member, can i encapsulate this on a single type using templates?


Now the code can be compiled with gcc

Thank you everybody

like image 590
jdavidls Avatar asked Nov 03 '22 22:11

jdavidls


1 Answers

is possible to reach C::b::a by a member pointer?

Sort of:

C c; 
A B::*ca = &B::a;  //    usage: c.b.*ca;  

is pointer inference chaining the only solution?

Yes

like image 112
Armen Tsirunyan Avatar answered Nov 12 '22 21:11

Armen Tsirunyan