How to get a member pointer from a class pointer and plain pointer to member in C++?

200 Views Asked by At

I can get plain pointer to a member of an object instance like in the example. How can I do it in the reverse direction?

struct S {
    int i;
};

// We have a pointer to an instance of S and an int member pointer in S.
// This function returns a pointer to the pointer member in the pointed object.
int* from_mptr(S* s, int S::* mp) {
    return &(s->*mp);
}

// How to implement this?
// We have the object pointer and a pointer to a member of this object instance.
// I would like to have a member pointer from these.
int S::* to_mptr(S* s, int* p) {
    // return ???
}

Technically it must be possible, because the difference between the object and the member on the instance is the member pointer. Although I don't know the correct syntax.

1

There are 1 best solutions below

0
On

Iterate over every single member of the structure that has the same type as the pointer and compare its address with the supplied pointer - if they match, return the appropriate member pointer. For the presented toy example:

int S::* to_mptr(S* s, int* p) {
    if (&s->i == p) {
       return &S::i;
    }
    return nullptr;
}