bool empty() const for ranges

Steven Schveighoffer schveiguy at gmail.com
Fri Nov 26 19:09:30 UTC 2021


On 11/26/21 5:44 AM, Salih Dincer wrote:
> Hi All;
> 
> I have two questions that make each other redundant. Please answer one 
> of them. I'm implementing ```bool empty() const``` for ranges as below:
> 
> ```d
>    bool empty() // const
>    {
>      bool result;
> 
>      if(!head)
>      {
>        result = true;
>        fastRewind();
>      }
>      return result; // head ? false : true;
>    }
> ```
> * Is the const essential for ranges?

No, there is no specification of whether any range methods have to be 
const. As Stanislav says, it is only a requirement that subsequent calls 
return the same value as long as popFront has not been called.

> * Is it possible to rewind the pointer (```Node * head;```) when my head 
> is empty by the const?

If const is set, then any members are treated as const, and anything 
they point to are treated as const. So no.

That being said, if `fastRewind` changes `empty` from true to false, the 
method is invalid.

-Steve


More information about the Digitalmars-d-learn mailing list