c++templatestemporary-objectsexpression-templates

How template expressions get rid of temporaries


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.


Solution

  • 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.