opIndex() may hide opSlice()
H. S. Teoh via Digitalmars-d
digitalmars-d at puremagic.com
Thu Mar 9 17:10:21 PST 2017
On Fri, Mar 10, 2017 at 01:07:33AM +0000, XavierAP via Digitalmars-d wrote:
> In their versions without parameters, these two operators would be
> called in the same way. If both are defined, opIndex() is called,
> regardless of lexical definition order, according to my test with DMD.
>
> If both (again I'm just talking about the overloads with no arguments)
> are defined within the same type, it's the fault of the author. But I
> would think the compiler should complain.
>
> They can also be inherited, which is sneakier.
>
> The web reference tersely says under its *Slice* Operator Overloading
> chapter [1]: "To overload a[], simply define opIndex with no
> parameters."
>
> Should not the overload of opSlice() with no arguments be deprecated?
> Am I missing something?
>
>
> [1] https://dlang.org/spec/operatoroverloading.html#array-ops
Using opSlice() for slicing (i.e., arr[]) is old, backward-compatible
behaviour.
The recommended usage is to use opSlice to transform range syntax (i.e.,
arr[1 .. 2]) into a type that opIndex understands, i.e.,
arr[1, 2..3, 4]
is translated to:
arr.opIndex(1, arr.opSlice(2,3), 4)
T
--
"I'm running Windows '98." "Yes." "My computer isn't working now." "Yes, you already said that." -- User-Friendly
More information about the Digitalmars-d
mailing list