banging my head on the c++, again
Sep. 2nd, 2008 08:02 pmIs 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?
no subject
Date: 2008-09-03 09:35 pm (UTC)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.no subject
Date: 2008-09-03 10:24 pm (UTC)