The difference between T[] opIndex() and T[] opSlice()

Steven Schveighoffer schveiguy at gmail.com
Tue Oct 3 16:45:39 UTC 2023


On 10/3/23 12:09 PM, Paul Backus wrote:
> On Tuesday, 3 October 2023 at 13:07:00 UTC, Steven Schveighoffer wrote:
>>
>> Now, you can define a further `opIndexAssign(T val, size_t idx)`. 
>> However, now you lose capabilities like `a[0]++`, which I don't think 
>> has a possibility of implementing using an `opIndex` operator, and it 
>> would be pretty ugly if you had to.
> 
> Works for me, with both `++` and `+=`: https://run.dlang.io/is/JckTVG
> 
> AST output confirms that these are lowered to use `opIndex`.
> 
> Looking at the spec, it seems like `opIndex` would only be pre-empted 
> here if you overloaded `opIndexUnary` (for `++`) and/or 
> `opIndexOpAssign` (for `+=`).

OK, so it's not as bad as I thought, but surely the compiler should 
recognize that `opIndexAssign(val, idx)` doesn't work, but `opIndex(idx) 
= val` does?

-Steve


More information about the Digitalmars-d-learn mailing list