Pitfalls of delegates inside ranges

Artur Skawina art.08.09 at gmail.com
Mon Sep 2 08:02:38 PDT 2013


On 09/02/13 16:43, Joseph Rushton Wakeling wrote:
>> In this case, there's no need for a delegate, as you do not want
>> to operate on the original object. So you can simply do:
>>
>>      //...
>>      private void function(ref typeof(this)) _jump;
>>      private void jump() { _jump(this); }
>>
>>      this(size_t max)
>>      {
>>          _max = max;
>>          _jump = &jump10;
>>      }
>>      //...
>>      static jump10(ref typeof(this)this_)
>>      {
>>          this_._count += 10;
>>          writeln("At end of jump, count = ", this_._count);
>>      }
>>
>> It's cheaper than the other alternative (updating ctx in cpctor),
>> but slightly more verbose. More importantly, AFAICT, this is a
>> better fit for the actual problem.
> 
> Oh, nice thought.  Thank you! :-)

I'm not sure where the delegates are supposed to be defined, the above
allows defining then externally. If that is not required and you only
need to select them from a set of predefined internal ones, then you can
use your original code with something like:

    private void function() _jump;
    private void jump() { void delegate() dg; dg.ptr=&this; dg.funcptr=_jump; dg(); }
    this(size_t max)
    {
        _max = max;
        _jump = (&jump10).funcptr;
    }

That way `jump10` (and any other such functions) can still use the implicit-
'this'.

/I/ would probably just wrap the function body in 'with (this_) {...}'.

artur 


More information about the Digitalmars-d-learn mailing list