"+=" (overloads) with custom array slices on both lhs, and rhs ??
Ali Çehreli
acehreli at yahoo.com
Sun Sep 5 21:06:49 UTC 2021
On 9/5/21 12:43 PM, james.p.leblanc wrote:
> I have constructed a custom array type that works, but is missing
> correct functioning on some operator overloads.
With its old, new, and newest styles; and support for multi-dimensional
use cases; operator overloading can be difficult to get right. Here is a
one-dimensional case that works:
struct MyArray(T) {
T[] elements;
this(size_t length) {
this.elements.length = length;
}
size_t opDollar() const {
return elements.length;
}
auto opSliceOpAssign(string op)(T value, size_t beg, size_t end) {
auto slice = elements[beg .. end];
mixin (format!q{
slice[] %s= value;
}(op));
return slice;
}
// For the entire range of elements
auto opSliceOpAssign(string op)(T value) {
// Dispatch to the other one
return this.opSliceOpAssign!op(value, 0, elements.length);
}
}
import std.stdio;
import std.format;
void main() {
auto m = MyArray!(int)(10);
m[2 .. 5] += 42;
writeln(m);
m[4 .. $] -= 100;
writeln(m);
m[] *= 2;
writeln(m);
}
Ali
More information about the Digitalmars-d-learn
mailing list