1

我可以像示例中那样获得指向对象实例成员的普通指针。我怎样才能在相反的方向做到这一点?

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

从技术上讲,它必须是可能的,因为对象和实例上的成员之间的区别在于成员指针。虽然我不知道正确的语法。

4

1 回答 1

2

迭代结构中与指针具有相同类型的每个成员,并将其地址与提供的指针进行比较 - 如果它们匹配,则返回适当的成员指针。对于呈现的玩具示例:

int S::* to_mptr(S* s, int* p) {
    if (&s->i == p) {
       return &S::i;
    }
    return nullptr;
}
于 2021-11-09T13:57:53.940 回答