zwol: stylized sketch of a face in profile (Default)
[personal profile] zwol

Is it possible in C++ to declare and initialize a pointer-to-member that points to a data member of a data member? Concretely, given

struct A { int x; int y; };
struct B { A i; A ii; A iii; A iv; };

I would like to be able to do something like this:

TYPE piix = INITIALIZER<B, ii, x>;
...
B b;
int x_within_ii = b.*piix;

Is this possible? If so, exactly how do you write TYPE and INITIALIZER? If not, why the hell not?

Date: 2008-09-03 09:35 pm (UTC)
From: [identity profile] marphod.livejournal.com
Aaaah.

No. There is no way, as there is no way to give a pointer a this pointer, in order to resolve it.


Now, there are ways around this.

You can make an offset table. Create an exmplar object of the desired type, and do
struct S{ int a; int b; };
S obj; // implicit default ctor
int offsets[] = { reinterpret_cast<int>(
                    (&dynamic_cast<S>(obj.a) - &dynamic_cast<S>(obj)),
                  reinterpret_cast<int>(
                    (&dynamic_cast<S>(obj.b) - &dynamic_cast<S>(obj))
                };

S obj2(foo, bar, baz, qux);
assert(&obj2.a == (&obj2 + offset[0]);
assert(&obj2.b == (&obj2 + offset[1]);
assert(obj2.a == (int)(*(int*)(&obj2 + offset[0])); // get lazy, I know.

Make a quick templated functor, and this can look cleaner.  Regardless it should work.

Date: 2008-09-03 10:24 pm (UTC)
From: [identity profile] zwol.livejournal.com
This is not helpful; you clearly still have no point of reference for my original question, and your suggestions are no good. [livejournal.com profile] falsedrow gave the answer I needed, so please just stop.

April 2017

S M T W T F S
      1
2345678
9101112131415
16171819 202122
23242526272829
30      

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 5th, 2026 03:18 am
Powered by Dreamwidth Studios