1

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.

Gábor
  • 71
  • 2
  • 2
    Your intuition is wrong - there is no way to take a pointer and find out which member, if any, it points to, and no way to create a pointer-to-member other than applying `&` to a class member. This looks suspiciously like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you ultimately trying to accomplish? – molbdnilo Nov 09 '21 at 13:36
  • it isnt that simple. Take a look at [`offsetof`](https://en.cppreference.com/w/cpp/types/offsetof). Even that is only possible via some compiler magic and afaik it cannot be used to get a pointer to member – 463035818_is_not_an_ai Nov 09 '21 at 13:38
  • what would be the use case? You have `int*` to `i` of one instance and want to access `i` of other instances? Maybe there is a different way to achieve your aim – 463035818_is_not_an_ai Nov 09 '21 at 13:40
  • You basically need to have a list of every `int S::*` pointer that exists and compare if `p` is one of those when dereferenced with `s`. Eventually, if C++ ever gets static reflection, it might become possible to implement this without manually implementing such a list. – François Andrieux Nov 09 '21 at 13:48
  • Is it _guaranteed_ that `int *p` is a pointer to an `int` member inside some instance of `struct S`? – KamilCuk Nov 09 '21 at 13:54

1 Answers1

2

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;
}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111