opIndexUnary post in-/decrement how to ?

wjoe invalid at example.com
Wed Jul 14 20:55:32 UTC 2021


On Wednesday, 14 July 2021 at 16:13:35 UTC, Tejas wrote:
> On Wednesday, 14 July 2021 at 15:08:56 UTC, wjoe wrote:
>> On Wednesday, 14 July 2021 at 14:50:01 UTC, Mike Parker wrote:
>>> On Wednesday, 14 July 2021 at 12:35:07 UTC, wjoe wrote:
>>>> [...]
>>>
>>> It's how the contract of post-inc/dec work---pre-inc/dec 
>>> return the modified value, post-inc/dec return the original 
>>> value.
>>>
>>> [...]
>>
>> That makes a lot of sense now, thank you!
>
> **IT WORKS NOW**
>
> Thanks vit for the ```ref``` idea!
>
> ```d
> import   std.stdio;
>
> struct abc{
>     int[100] a;
>     static int temp;
>     ref/*notice this ref*/ int opIndex(int index)return/*NOTICE 
> THE RETURN*/ {
>         return a[index];
>     }
>     int opIndexUnary(string s)(int index)
>         if(s == "++"){
>         return ++a[index];
>         }
>     int[] opUnary(string s)() if (s == "++"){
>         return a[] += 1;
>     }
> }
>
> void main (){
>     abc s;
>
>     writeln(s[0]++);// doesn't work for some reason EDIT: IT 
> NOW WORKS!!!!!!!!
>
>     writeln(s[0]);
>     writeln(++s[0]);
>
>    // writeln(s++);//but this works!!
>
>    // writeln(s);
> }
>
> ```

Congratulations:) Unfortunately I haven't got anything I could 
return by ref so I can't take advantage of a low hanging fruit.
In my book overloading operators is no fun - at all - and always 
a last resort because it requires so much time and testing and 
causes so many headaches.

Workarounds exist like ```i[n] += 1``` or direct call via 
```i.opIndexUnary!"++"(n)``` or simply ```++i[n]```.
But that's beside the point. There's nothing in the spec that 
says something about something needs to be returned by ref.
Rewriting manually compiles and works as intended. So clearly 
something else is going on which makes the compiler select 
```opIndex``` over ```opIndexUnary``` rewriting it post to pre.
In my particular case the compiler can rule out ```opIndex``` so 
why does it abort instead of trying ```opIndexUnary``` ? Or was 
it trying and it didn't work ? If that's the case I'd like to 
know the reason why it discarded ```opIndexUnary```.

Anyways all the answers so far are much appreciated!


More information about the Digitalmars-d-learn mailing list