Proposal: Operator overloading without temporaries

xs0 xs0 at xs0.com
Tue Mar 28 08:24:58 PST 2006


James Dunne wrote:
> If possible, can someone lay out a clear definition of both "array 
> expressions" and "expression templates"?  I'd really like to fully 
> understand what's possible in this area for my own research.
> 
> Thanks,
> 

afaik, array expressions are just expressions which get evaluated 
element-wise over whole arrays:

a[] = b[] + c[]; // must be same length

is the same as

for (int i=0; i<a.length; i++)
     a[i] = b[i] + c[i];

The advantage of having them instead of doing for loops (in addition to 
aesthetics) is that the compiler can optimize the code much better (for 
example, by doing vectorization == AltiVec/MMX/SSE), because it clearly 
knows what you're doing - with a for loop, it's just a bunch of 
single-element operations.


Expression templates, otoh, are a somewhat complex template technique, 
which allows efficient evaluation of expressions over arbitrary types. 
Instead of evaluating the expression one operation at a time:

a = b + c * d

usually becomes

_t1 = c.opMul(d);
_t2 = b.opAdd(_t1);
a = _t2

the expressions first evaluate to template instances, which can then be 
inlined and optimized by the compiler. That obviously results in faster 
execution. The above example would become something like:

auto expr=Sum!(b, Product!(c, d));
a.length=expr.length;
for (int i=0; i<a.length; i++)
     a[i]=expr.evaluate(i); // hopefully inlines to b[i]+c[i]*d[i]

http://osl.iu.edu/~tveldhui/papers/Expression-Templates/exprtmpl.html

One problem in doing them in D is that you can't overload the = 
operator, so the best one can hope for is

(b+c*d).assignTo(a);
// or
a = (b+c*d).eval();

Another problem is that expression templates rely heavily on implicit 
instantiation, which is currently quite basic in D (but getting better).


Hope that helped :)


xs0



More information about the Digitalmars-d mailing list