Member delegate/fp to another member in same object?

Juanjo Alvarez via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 2 10:08:11 PDT 2017


Hi!

I would like to have a "proxy" delegate, let's call it "foo" that 
could point to a method or another, let's call them "fast_foo" or 
"slow_foo" on the same object. This way depending on some 
conditions I could switch at runtime from one set of methods to 
others with a "switchFoo(" fast") method while the rest of the 
code inside the object would continue happily calling "foo".

The problem I have is that since the delegate keep the state of 
the object at the moment of the assignment I can't use it for 
this is pretty since the "fast/slow" methods need the value of 
the members of the enclosing object members at the point of 
usage,  I guess that I could pass the "this" pointer in the 
rebinding method but since the targets are also methods of the 
same object I wouldn't be surprised to find that there is an 
obvious/elegant  way to get access to "this" on the 
delegate-pointed method implementing.

Example:

struct S {
   int someState;
   void some_foo() { return this. someState;}

   void delegate() foo;

   void enable() {
     foo = &some_foo;
   }
}

unittest {
   S s;
   s.someState = 1;
   enable();
   s.someState = 2;
   assert(foo == 2);
   // fails because the delegate keeps
   // the state of the object at the
   // assignment point
}




More information about the Digitalmars-d-learn mailing list