I’ve never seen this in any language, but I was wondering if this is possible using some trick that I don’t know.
Let’s say that I have a function like
struct A {
// some members and methods ...
some_t t;
// more members ...
};
void test(some_t& x) { // a reference to avoid copying a new some_t
// obtain the A instance if x is the t member of an A
// or throw an error if x is not the t member of an A
...
// do something
}
Would it be possible to obtain the instance of A whose member t is x ?
If you know that you have a reference to the
tmember of someAinstance, you can get the instance usingcontainer_of, e.g.A* pa = container_of(&x, A, t);.Verifying that the resulting pointer actually is an
Ais technically possible if and only ifAhas virtual members, unfortunately there’s no portable method to check.You can achieve something similar, however, using multiple inheritance and
dynamic_cast, which allows cross-casting between subobjects.