Is it possible to return mutable and const range from a single method?

realhet real_het at hotmail.com
Mon Aug 22 16:36:46 UTC 2022


Hello,

I managed to make a universal getParent() function which can 
preserve constness.
I also had success with inout functions that work with this inout 
getParent method.
Is it possible to do something like this but for the allParents 
input range producer method?
In the const range implementation, the internal storage is 
non-const, it is just implicitly converted to const in the 
front() property.
It gives the protection I was needed but is it possible to make 
this prettier?


```d
import std;

class A{
     inout(A) getParent() inout{ return null; }

     this(A p){
     }
}

class B : A{
     A parent;

     override inout(A) getParent() inout{ return parent; }

     auto allParents(){
       struct ParentRange{
         A act;
         @property bool empty() const{ return act is null; }
         @property A front() { return act; }
         void popFront(){ act = act.getParent; }
       }
       return ParentRange(getParent);
     }

     auto allParents()const {
       struct ConstParentRange{
         A act;
         @property bool empty() const{ return act is null; }
         @property const(A) front() inout { return act; }
         void popFront(){ act = act.getParent; }
       }
       return ConstParentRange(cast()getParent);
     }

     this(A p){
         super(p);
         parent = p;
     }
}

auto test(inout A a, void delegate(inout A) fun){
     auto p = a.getParent;
     fun(p);
}

void main()
{
     auto a = new A(null);
     auto b = new B(a);

     const c = b;

     writeln(c.getParent);
     c.test((in d){ writeln(d); });

     writeln;
     c.allParents.each!writeln;
     writeln;
     b.allParents.each!writeln;

}
```


More information about the Digitalmars-d-learn mailing list