Re: Expression Templates
On Jul 31, 1:04 pm, Michael DOUBEZ <michael.dou...@free.fr> wrote:
madhu.srikka...@gmail.com a =E9crit :
I came across a paper by Angelika Langer in C++ Users Journal on
Expression Templates.
In the article she had mentioned that the code snippet below
used to calculate a dot product is an expression template.
[...]
Is this actually an expression template or this just a case
of template meta programming since this doesn't overload the
function operator.
IMO template meta programming deals broadly with operations on
type while expression template focuses on template to provide
faster and more expressive code.
I'm not sure, but I'd generally consider expression templates as
a subset of template metaprogramming. Generally, I'd consider
anything which involves "writing code for the compiler" in
templates as template meta-programming.
But it really is a question of vocabulary, and I don't think
that there's any one correct answer.
(Note too that much of what is now known under the name of
expression templates was being done before templates existed,
with inheritance. Since all of the derived types ended up being
used as temporary objects, on the stack, the compiler always
knew the exact type, and could inline the functions anyway, even
though they were virtual.)
Code above would have been also written:
template <class T>
inline dot(int site,T* a, T* b)
{
T ret=T();
for(int i=0;i<size;++i)
{
ret+=a[i]*b[i];
}
}
cout << dot(4,a,b);
Unless you have some aggressive optimization (inlining, loop
unrolling ...), the code is more likely to create temporaries
and other sub-optimal constructs.
Well... maybe not for this simple example:-). But as soon as
you start doing more complex things, yes. You save a lot of
intermediate temporaries, and it's very, very difficult for the
compiler to eliminate them itself.
And the alternative:
cout<< (a[0]*b[0]+...+a[3]*b[3])<<endl;
is cumbersome and doesn't give the meaning of what you do.
And becomes impossible as soon as the dimension ceases to be a
compile time constant.
Using dot<4>(a,b) expand nicely to a[0]*b[0]+...+a[3]*b[3] while
retaining the meaning.
My understanding of expression templates may be a bit hazy
as I don't have access to books on the topic as of now.
Would be glad if someone here can throw more light on this.
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Expression-template
Wouldn't it be better to refer him to some original sources,
like Todd Veldhuizen's original article
(http://ubiety.uwaterloo.ca/~tveldhui/papers/Expression-Templates/
exprtmpl.html).
There's also considerable treatment in the Vandevoorde and
Josuttis.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34