Proposal: Operator overloading without temporaries

James Dunne james.jdunne at gmail.com
Tue Mar 28 11:25:06 PST 2006


xs0 wrote:
> 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

Yes, thank you very much!

-- 
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCS/MU/S d-pu s:+ a-->? C++++$ UL+++ P--- L+++ !E W-- N++ o? K? w--- O 
M--@ V? PS PE Y+ PGP- t+ 5 X+ !R tv-->!tv b- DI++(+) D++ G e++>e 
h>--->++ r+++ y+++
------END GEEK CODE BLOCK------

James Dunne



More information about the Digitalmars-d mailing list