0

I was reading some articles and in many of them mentioned about expression templates can avoid using temporary objects. But none of them mentioned how this is done. As far as I know, due to the design architecture operations are done using temporary object. For example, if a, b and c are two matrix and if we do a = b+c then the result of b+c is kept in a temporary object like temp = b+c and then result is copied back to a like a = temp.

But if we use expression templates then this addition(+) operation returns reference of b and c and then the main calculation happen when assignment operator(=) is evaluated. This is the simple general concept of template expression. But I don't understand how it get rid of temporary objects. It would be nice if someone could give just the general idea how this temporary is avoided.

  • 1
    You might find [this answer](http://stackoverflow.com/a/11812468/1322972) to a related, but non-duplicate question, interesting. – WhozCraig Jul 10 '16 at 09:56
  • You still get a temporary object, but not of the final type, you have a temporary wrapper. – Jarod42 Jul 10 '16 at 13:59

1 Answers1

2

Take the example of

Vector a,b,c,d;
a = b + c + d;

Usually this would translate into something like

a = b.operator+( c.operator+(d) );

where each call to operator+ would have to loop through the entries. However, the more natural way would be to loop through all elements once and do some addition like

a_i = b_i + c_i + d_i

and thats what expression templates effectively do by evaluating an epxression only when the result is really needed.

Note that the temporary (ie intermediate result of c+d) is only required because each operator+ seperately loops through all elements. Once the seperate loops are combined, there is no need for a temporary anymore.

For a less amateurish explanation and more details I can suggest you this talk from the CppConf 2015.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185