W
Walt Karas
Is this code legal under the standard?
struct A
{
int i;
struct C
{
unsigned offset_of_c(void) { return((unsigned) &(((A *) 0)->c)); }
A * ptr_to_containing_A_instance(void)
{ return((A *) (((char *) this) - offset_of_c())); }
void set(void)
{ ptr_to_containing_A_instance()->i = 10; }
}
c;
};
#include <stdio.h>
int main(void)
{
A a;
a.c.set();
// Should print 10.
printf("%d\n", a.i);
return(0);
}
The version of GCC I am using compiles and links it,
and the resulting executable produces the expected
output when run.
Is there a less ugly way to implement a class that
is not only a member class but whose instance must
be in the containing class and access the containing
class's members?
struct A
{
int i;
struct C
{
unsigned offset_of_c(void) { return((unsigned) &(((A *) 0)->c)); }
A * ptr_to_containing_A_instance(void)
{ return((A *) (((char *) this) - offset_of_c())); }
void set(void)
{ ptr_to_containing_A_instance()->i = 10; }
}
c;
};
#include <stdio.h>
int main(void)
{
A a;
a.c.set();
// Should print 10.
printf("%d\n", a.i);
return(0);
}
The version of GCC I am using compiles and links it,
and the resulting executable produces the expected
output when run.
Is there a less ugly way to implement a class that
is not only a member class but whose instance must
be in the containing class and access the containing
class's members?