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

Steven Schveighoffer schveiguy at gmail.com
Mon Aug 22 19:35:11 UTC 2022


On 8/22/22 12:36 PM, realhet wrote:
> 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?

Technically your code is a reasonable compromise. The two versions are 
different enough that it might not make sense to combine them.

It is possible to write the same function for both const and mutable 
overloads by using the `this` template parameter:

```d
import std.stdio;
class C
{
    void foo(this This)(string s) {writefln("for %s this is %s", s, 
This.stringof); }
}

void main()
{
    auto c = new C;
    c.foo("mutable");
    const c2 = c;
    c2.foo("const");
}
```

But your common code is going to have a few static ifs in it, simply 
because const class instances are not assignable.

You might find some success with std.typecons.Rebindable.

-Steve


More information about the Digitalmars-d-learn mailing list