Why no acess to other structs in classes?

BCS BCS at pathlink.com
Mon Nov 6 09:09:11 PST 2006


Bill Baxter wrote:
> Bill Baxter wrote:
> 
[...]
> Ok ok.  I was wrong.  It is a little more complicated than that.  If you 
> have two instances of S inside the class, then you'd need two instances 
> of the method outer_a, each with it's own compile time offsets.  But 
> then something like
> 
>    outer_a() {
>       static int num_calls++;
>       ...
>    }
> 
> would fail

another case where the constant offset assumption will fail

class C
{
   int a;
   struct S {
     int b;
     int f() { return b+1; }
     int outer_a() {
       return cast(int)* (cast(char*)(&b)-int.sizeof);
   }

   /*static*/ void other()
   {
      S foo;
      foo.outer_a();
      S* bar;
      bar.outer_a();
   }

}

> 
> One solution would be to add the hidden pointer-to-outer member to any 
> structs that use the "outer" property.  If you don't use it, you don't 
> pay for it.  Rather like how virtual functions are handled in C++.  If 
> you don't declare any methods to be virtual, then the compiler doesn't 
> generate a vtable.
> 

Ouch, I am a big fan of the "struct are just data" approach. I would 
rather, on the rare occasion this would be used, give up a bit of speed 
and go with objects than add hidden overhead to structs.


> In the mean time, the obvious workaround is to give the structs a 
> pointer to the outer class yourself.
> 
> class C
> {
>     int a;
>     this() {
>         s.outer = this;
>         s2.outer = this;
>     }
>     struct S {
>         int b;
>         int whats_A() {
>             this.b += 1;
>             return outer.a;
>         }
>         C outer;
>     }
>     S s;
>     S s2;
> }
> 

That would also be a good solution



More information about the Digitalmars-d-learn mailing list