Member functions with access to local variables

Linden Krouse ztaticnull at gmai.com
Mon Apr 8 16:43:44 PDT 2013


Hello! While working on a project of mine, I ran into a situation 
where it would be beneficial and elegant to call a function with 
access to the caller's local variables. Of course D supports this 
with nested functions but the function to be called needs to have 
access to the private variables of another object. In fact the 
function should be a member function of the second class, 
although then it would need to be passed many (6+) variables, 
most of which will not be needed in most cases. I know another 
solution would be sacrificing encapsulation and increase the 
visibility of the members of the second class but that seems much 
less elegant. Splitting the function into smaller functions is 
also not possible as what variables are needed is determined by 
the second object at runtime.
So...

Is there a way to have a function be both a nested function and a 
member function of a different class?

Perhaps something like

class A
{
     B b = new B();
     int foo()
     {
         int x = 0;
         b.bar();
         return x; //returns 5
     }
}

class B
{
     private int y = 5;
     void A.foo:bar()
     {
         x += y;
     }
}

if there isn't already a way to do this.


More information about the Digitalmars-d mailing list