Given a class instance and pointer to a field we can obtain regular pointer pointing to field variable of this class instance - as in last assignment in following code;
class A
{
public:
int i, j;
};
int main(){
A a;
int A::*p = &A::i;
int* r = &(a.*p); // r now points to a.i;
}
Is it possible to invert this conversion: given class instance A a;
and int* r
obtain int A::* p
(or NULL ptr if pointer given is not in instance given) as in code:
class A
{
public:
int i, j;
};
int main(){
A a;
int A::*p = &A::i;
int* r = &(a.*p); // r now points to a.i;
int A::*s = // a--->r -how to extract r back to member pointer?
}
The only way that I can think of doing it, would be to write a function that takes every known field of A, calculates it's address for given instance and compares with address given. This however requires writing custom code for every class, and might get difficult to manage. It has also suboptimal performance.
I can imagine that such conversion could be done by compiler in few operations under all implementations i know - such pointer is usually just an offset in structure so it would be just a subtraction and range check to see if given pointer is actually in this class storage. Virtual base classes add a bit of complexity, but nothing compiler couldn't handle I think. However it seems that since it's not required by standard (is it?) no compiler vendor cares.
Or am I wrong, and there is some fundamental problem with such conversion?
EDIT:
I see that there is a little misunderstanding about what I am asking about. In short I am asking if either:
- There is already some implementation of it (at the compiler level I mean), but since hardly anybody uses it, almost nobody knows about it.
- There is no mention of it in standard and no compiler vendor has though of it, but In principle it is possible to implement (once again: by the compiler, not compiled code.)
- There is some deep-reaching problem with such an operation, that I missed.
My question was - which of those is true? And in case of the last - what is underlying problem?
I am not asking for workarounds.