opIndexUnary post in-/decrement how to ?

Tejas notrealemail at gmail.com
Thu Jul 15 12:09:20 UTC 2021


On Thursday, 15 July 2021 at 11:02:17 UTC, wjoe wrote:
> On Thursday, 15 July 2021 at 04:07:49 UTC, Tejas wrote:
>> Your code
>> ```d
>> auto x = i[1]++;
>> ```
>> Expands to:
>> ```d
>> auto x = (auto e = i[1]/*notice opIndex*/, ++i[1]/* notice 
>> opIndexUnary*/, return e;);
>> ```
>>
>> This doesn't happen with pre increment. No compiler 
>> shenanigans.
>
> Interesting to see it spelt out like this (your remarks are 
> very enlightening) so I just went one step further and rewrote 
> this line like so:
> ```D
> i[1] = 3;
> auto x = (){auto e = i[1]; ++i[1]; return e;}();
> assert (i[1] == 4 && x == 3);
> ```
> This just works. But I don't think this is what happens. What I 
> think happens is that the compiler rewrites ```i[1]++`` to 
> something like this:
> ```D
> i.opIndex(1).opUnary!"++"();
> ```
> plus all the other shenanigans.
>


Oh yes, that is what happens. I was trying to be a little concise.
You are correct, this is what the code will look in the gory 
details (I believe) :
```d
auto x = (auto e = i.opIndex(1), i.opIndexUnary("++")(1)/*this 
may or may not expand to what you wrote, not sure what the 
compiler does, although what you say does sound like the obvious 
thing to do*/, return e);
```
> I did indeed override opIndex() but since i need to apply a bit 
> mask and do some shifting I can't return anything by ref.

As I mentioned, maybe the bit manipulation library could 
help(although they don't seem to be overloading the operators in 
the first place, thus sidestepping the problem you encountered).


More information about the Digitalmars-d-learn mailing list