如何在C++中从类指针和指向成员的普通指针中获取成员指针



我可以像示例中那样获得指向对象实例成员的普通指针。我怎么能反方向做呢?

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;
}

相关内容

  • 没有找到相关文章

最新更新