inout and opApply

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Fri Jun 24 07:06:24 PDT 2016


On 6/24/16 2:08 AM, Shachar Shemesh wrote:
> On 24/06/16 01:22, Steven Schveighoffer wrote:
>
>> Considering the possible use cases for something like this, I think we
>> are better off having this limitation than not being able to use opApply
>> with inout.
>>
>
> I am not sure I followed the discussion correctly. If I did, however, it
> seems to me the following would also become impossible:
>
> size_t numElements(T)(const ref T val) {
>   size_t num;
>
>   foreach(i; val) {
>     num++;
>   }
>
>   return num;
> }

No, this will work fine. Examine the opApply function again:

int opApply(scope int delegate(ref inout T) dg) inout

Note that the delegate itself is NOT marked inout. Just the parameter it 
takes is (and the aggregate). The compiler is going to enforce that 
while inside opApply, the structure itself is inout, and not mutable. 
However, your delegate will not be inout (or const), and can modify 
whatever it likes in terms of your function attributes. The compiler 
simply allows the implicit wrapping using inout from `int delegate(ref 
const T)` to `int delegate(ref inout T)`.

-Steve


More information about the Digitalmars-d mailing list