我可以像示例中那样获得指向对象实例成员的普通指针。我怎么能反方向做呢?
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 ???
}
从技术上讲,这一定是可能的,因为对象和实例上的成员之间的区别在于成员指针。虽然我不知道正确的语法。
遍历结构中与指针类型相同的每个成员,并将其地址与提供的指针进行比较-如果匹配,则返回相应的成员指针。对于所展示的玩具示例:
int S::* to_mptr(S* s, int* p) {
if (&s->i == p) {
return &S::i;
}
return nullptr;
}