Intermediate results using expression templates

2019-01-25 22:07发布

问题:

in C++ Template Metaprogramming : Concepts, Tools, and Techniques from Boost and Beyond

... One drawback of expression templates is that they tend to encourage writing large, complicated expressions, because evaluation is only delayed until the assignment operator is invoked. If a programmer wants to reuse some intermediate result without evaluating it early, she may be forced to declare a complicated type like:

Expression<
           Expression<Array,plus,Array>,
           plus,
           Expression<Array,minus,Array>
          > intermediate = a + b + (c - d);

(or worse). Notice how this type not only exactly and redundantly reflects the structure of the computationand so would need to be maintained as the formula changes but also overwhelms it? This is a long-standing problem for C++ DSELs. The usual workaround is to capture the expression using type erasure, but in that case one pays for dynamic dispatching. There has been much discussion recently, spearheaded by Bjarne Stroustrup himself, about reusing the vestigial auto keyword to get type deduction in variable declarations, so that the above could be rewritten as:

auto intermediate = a + b + (c - d);

This feature would be a huge advantage to C++ DSEL authors and users alike...

Is it possible to solve this problem with the current c++ std. (non C++0X)

For Example i want to write a Expression like:

Expr X,Y

Matrix A,B,C,D

X=A+B+C

Y=X+C

D:=X+Y

Where operator := evaluate the expression at the latest Time.

回答1:

For now, you can always use BOOST_AUTO() in the place of C++0x's auto keyword to get intermediate results more easily.

Matrix x, y;
BOOST_AUTO(result, (x + y) * (x + y)); // or whatever.


回答2:

I don't understand your question. auto is going to be reused in C++0x for automatic type inference.

I personally see this as a drawback for expression templates since they often relay on having a smaller life span than the objects they are built upon which can turn out to be false if the expression template is captured as I explain here.