Thread overview
bool empty() const for ranges
Nov 26, 2021
Salih Dincer
Nov 26, 2021
Stanislav Blinov
November 26, 2021

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:

  bool empty() // const
  {
    bool result;

    if(!head)
    {
      result = true;
      fastRewind();
    }
    return result; // head ? false : true;
  }
  • Is the const essential for ranges?
  • Is it possible to rewind the pointer (Node * head;) when my head is empty by the const?

Thanks...

November 26, 2021

On Friday, 26 November 2021 at 10:44:10 UTC, Salih Dincer wrote:

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

empty is not required to be const, but it is required to yield the same result if called multiple times without mutating the range (see https://dlang.org/phobos/std_range_primitives.html#.isInputRange). In other words, you really ought not to mutate the range in implementation of empty, or at least not to the extent you seem to want to.

November 26, 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:

   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