Ranges: is it ok if front is a data member?

Marco Leise Marco.Leise at gmx.de
Fri Dec 13 07:52:31 PST 2013


Am Thu, 12 Dec 2013 08:43:35 -0800
schrieb "H. S. Teoh" <hsteoh at quickfur.ath.cx>:

> I do this with my own ranges sometimes. Sometimes, it's more performant
> to precompute the value of .front and store it (as .front), and have
> .popFront compute the next value, than to have .front compute the value
> every time. AFAICT, this is perfectly fine and should work with Phobos
> seamlessly. The power of ducktyping!
> 
> 
> T

Most non-trivial ranges do the actual work in `popFront()' and
return a cached value from `front'. It has been argued as a
design quirk, that this in general leads to:

struct Range
{
  bool popFrontHasBeenCalledOnce = false;
  T current;

  @property T front()
  {
    if (!popFrontHasBeenCalledOnce)
    {
      popFront();  // initializes `current'
    }
    return current;
  }

  […]
}

-- 
Marco



More information about the Digitalmars-d-learn mailing list