getNext

Steven Schveighoffer schveiguy at yahoo.com
Tue Jul 13 06:34:32 PDT 2010


On Tue, 13 Jul 2010 08:54:07 -0400, Michel Fortin  
<michel.fortin at michelf.com> wrote:

> On 2010-07-13 00:38:55 -0400, Andrei Alexandrescu  
> <SeeWebsiteForEmail at erdani.org> said:
>
>> Yah, truth be told getNext won't win a prize for brevity. You need to  
>> define both a variable and a pointer to use it:
>>  T meh;
>> T * neh;
>> while ((neh = getNext(r, meh))) {
>>     ... process *neh ...
>> }
>
> At this point what you want is to use a foreach loop. In fact, if  
> foreach could be made to work with getNext (and it should), you'd rarely  
> need to write that boilerplate code yourself.

struct InputForeach(R) if(isInputRangeThatUsesGetNext!R)
{
    private R* range;
    this(ref R range) {this.range = &range;}
    int opApply(scope int delegate(ref ElementType!R) dg)
    {
       ElementType!R buf;
       ElementType!R *e;
       int result = 0;
       while(!result && (e = getNext(*range, buf)))
       {
          result = dg(*e);
       }
       return result;
    }
}

InputForeach!R inputForeach(R)(ref R r) if(isInputRangeThatUsesGetNext!R)  
{ return InputForeach!R(r); }


foreach(e; inputForeach(r))
{
    ...
}

opApply to the rescue :)

Of course, native support would be better, unless the compiler decides to  
start inlining opApply.

-Steve


More information about the Digitalmars-d mailing list