opSlice() or opIndex() for the entire slice?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Sep 4 12:12:27 PDT 2014
The documentation says "To overload a[], simply define opIndex with no
parameters":
http://dlang.org/operatoroverloading.html#Slice
And it works with some uses of a[]. However, opSlice() seems to be
needed to actually use the returned slice further.
Note that opSlice() also seems to be for backward compatibility: "For
backward compatibility, a[] and a[i..j] can also be overloaded by
implementing opSlice() with no arguments and opSlice(i, j) with two
arguments, respectively. This only applies for one-dimensional slicing,
and dates from when D did not have full support for multidimensional
arrays. This usage of opSlice is discouraged."
How can I achieve the last line in main() without needing opSlice()? I
am trying to let the Slice type handle opAssign() and friends.
import std.stdio;
struct Collection
{
int[] elements;
/* Handles the slice operations */
struct Slice
{
int[] slice;
Slice opAssign(int value)
{
slice[] = value;
return this;
}
}
Slice opIndex()
{
writeln("opIndex");
return Slice(elements);
}
Slice opSlice()
{
writeln("opSlice");
return Slice(elements);
}
}
void main()
{
auto c = Collection([ 0, 1, 2, 3]);
// This works with either operator but opIndex is favored. (You can
// comment out opSlice() and it will still work.)
writeln(c[]);
// This requires opSlice.
c[] = 42;
}
Ali
More information about the Digitalmars-d-learn
mailing list