Operator overloading -- lets collect some use cases
Yigal Chripun
yigal100 at gmail.com
Thu Jan 1 14:12:46 PST 2009
Andrei Alexandrescu Wrote:
> Don wrote:
> > Weed wrote:
> >> Frits van Bommel пиÑеÑ:
> >>> Don wrote:
> >>>> Frits van Bommel wrote:
> >>>>> Don wrote:
> >>>>>> A straightforward first step would be to state in the spec that "the
> >>>>>> compiler is entitled to assume that X+=Y yields the same result as
> >>>>>> X=X+Y"
> >>>>> That doesn't hold for reference types, does it?
> >>>> I thought it does? Got any counter examples?
> >>> For any class type, with += modifying the object and + returning a
> >>> new one:
> >>
> >> The += operator too should return the object (usually "this")
> >
> > ALWAYS 'this'. It's another feature of operator overloading which is
> > redundant.
>
> Well as well as you yourself noticed in an older discussion,
> consistently returning "this" clashes with expression templates. But
> then IMHO the existence of "auto" makes it imperative that we find a
> better solution than expression templates.
>
> Changing gears, let's work on a simple example. Say we define a struct
> Vector and we want the following to be as fast as hand-coded:
>
> Vector a, b, c;
> double alpha = 0.5;
> ...
> a = b + alpha * c;
>
> The reference hand-coded implementation is:
>
> enforce(a.length == b.length && b.length == c.length);
> foreach (i; 0 .. a.length)
> {
> a[i] = b[i] + alpha * c[i];
> }
>
> All right, let's do this with operator overloading :o). Ideas? I have a
> couple, but I don't want to introduce bias.
>
>
> Andrei
Here's my first attempt:
struct Vector {
double[] arr; // internal array
opMul_r(double val) {
for (int i; i < arr.size(); ++i) {
yield val.opLazyMul(arr[i]);
i++;
}
}
opAdd(Vector other) {
for (int i; i < arr.size(); ++i) {
yield arr[i].opLazyAdd(other[i]);
i++;
}
}
...
}
the idea in the [pseudo-] code above is:
a) built-in types (double in the above) provide lazy ops.
so, for example, double.opLazyAdd will look similar to this:
double opLazyAdd(double other) { return double apply() { return this + other; }; }
note: there should be syntax for this: first thought - @op, like in 5 @+ 6;
b) generators expressed with yield.
think of this as expression templates with parts of it inside the compiler.
More information about the Digitalmars-d
mailing list