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

Jonathan M Davis jmdavisProg at gmx.com
Thu Dec 12 22:55:28 PST 2013


On Thursday, December 12, 2013 17:19:28 Adam D. Ruppe wrote:
> Consider the following:
> 
> struct JustZeroes {
>      int front = 0;
>      enum bool = false;
>      void popFront() {}
> }
> 
> Is that guaranteed to work as an input range? I ask because I've
> so often written:
> 
>    T current;
>    @property T front() { return current; }
> 
> that it just seems silly to me to write the extra lines when
> current == front. I realize there is a small difference there, in
> that front is not an lvalue here, but is when it is a direct
> member, but other than that, is this an acceptable form? Or does
> the lvalue thing mean it is strongly discouraged?

It's perfectly fine as far as isInputRange goes.

template isInputRange(R)
{
    enum bool isInputRange = is(typeof(
    (inout int = 0)
    {
        R r = void;       // can define a range object
        if (r.empty) {}   // can test for empty
        r.popFront();     // can invoke popFront()
        auto h = r.front; // can get the front of the range
    }));
}


All that's required with regards to front is

auto h = r.front;

That works perfectly fine with a variable. The primary reason to avoid it is 
encapsulation, but if you aren't worried about that, then it should work just 
fine to have front as a public member variable.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list