Mutable ForwardRange save() method not callable using const object

Timoses timosesu at gmail.com
Tue Sep 4 13:53:58 UTC 2018


Hey,

I'm fiddling around with ranges a bit and am wondering why save 
is not callable on a const object:

     class Range
     {
         ForwardRange!(const uint) offsets;

         this(const S s)
         {
             this.offsets = s.s.map!(e => e.i).inputRangeObject;
         }

         this(const Range a) // ERROR line 22
         {
             this.offsets = a.offsets.save;
         }

         Range save()
         {
             return new Range(this);
         }
     }
     struct I
     {
         uint i;
     }
     struct S
     {
         I[] s = [I(1), I(2), I(3)];
     }

     unittest
     {
         S s;
         auto a = new Range(s);
     }

onlineapp.d(22): Error: mutable method 
std.range.interfaces.ForwardRange!(const(uint)).ForwardRange.save 
is not callable using a const object
onlineapp.d(22):        Consider adding const or inout to 
std.range.interfaces.ForwardRange!(const(uint)).ForwardRange.save


In this case the Forwardrange Offsets is a
ForwardRange of MapResult(I => uint) of I[]

Since the type of MapResult.front is uint, the ForwardRange is 
essentially a uint[] array.

I could imagine that save is not marked as const because it is 
uncertain whether any indirections are part of the content..? But 
couldn't the compiler check that?

Could anybody explain what exactly is going on? Is there a reason 
the `save()` is not working on const objects?


Given that I haven't done much with ranges yet, any feedback on 
the above implementation is also greatly appreciated (it's just a 
reduced example).


More information about the Digitalmars-d-learn mailing list