nested inout return type

Simon Bürger via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 14 06:22:45 PDT 2016


On Tuesday, 14 June 2016 at 01:50:17 UTC, Era Scarecrow wrote:
> On Monday, 13 June 2016 at 23:51:40 UTC, Era Scarecrow wrote:
>>      inout(Slice) opSlice(size_t a, size_t b) inout
>>      {
>>          return cast(inout(Slice)) Slice(ptr+a, b-a);
>>      }
>
>  Seems the pointer has to be force-cast back to a normal 
> pointer so the constructor can work. (Because the function is 
> inout, ptr becomes inout(T*) )
>
>      return cast(inout(Slice)) Slice(cast(T*)ptr+a, b-a);
>
>  Beyond that it works as expected :) Writeln gives the 
> following output on Slice with opSlices:
>
> Slice!int(18FD60, 10)
> const(Slice!int)(18FD60, 10)
> immutable(Slice!int)(18FD90, 10)

Then instead of Slice!(const(T)) one would use const(Slice!T). 
Then there is no analogue of the following:

const(T)[] s = ...
s = s[5..7]

which is quite common when parsing strings for example. Still, 
might be the cleanest approach. However I found another solution 
for now without using any "inout":

* only do one mutable version of opSlice
* add implicit cast (using "alias this") for const(Slice!T) -> 
Slice!(const(T)).

So when trying to opSlice on a const it will first cast to a 
mutable-slice-of-const-elements and then do the slice. This is 
closer to the behavior of "const(T[])", though it might have 
issues when using immutable and not only const. Not sure.

Anyway, thanks for the help, and if someone cares, the full 
resulting code is on github.com/Krox/jive/blob/master/jive/array.d




More information about the Digitalmars-d-learn mailing list