表达式模板
表达式模板(Expression Templates)
释义
什么是“表达式模板(Expression Templates)”?这是一种以优美的inline表达式取代丑陋的Callback的技巧。例如,在一般情况下,我们用如下方式求一个积分:
doublef(doublex)
{
return x/(1.0+x);
}
doubleresult = integrate(f, 0.0, 10.0);
但是,有了“表达式模板(ExpressionTemplates)”,我们可以这样做:
DoublePlaceholder x;
doubleresult = integrate(x/(1.0+x), 0.0, 10.0);
如果我们预先定义好了一个DoublePlaceholder _x(多数情况下我们会这么做),我们只需如此:
doubleresult = integrate(_x/(1.0+_x), 0.0, 10.0);
看起来很美,是吧?是怎么做到的呢?
原理参考Todd Veldhuizen的《ExpressionTemplates》
优点
便利:
更加优美的语法。 高性能:比Callback有更好的性能。
特别在Vector、Matrix等向量运算时,可减少临时Vector/Matrix的生成,从而大大提高性能。作者(Todd Veldhuizen)在Blitz++中使用了该技巧。
应用:
Blitz++, a C++ class library for scientific computing which provides performance on par with Fortran 77/90) PETE, the Portable ExpressionTemplates Engine
POOMA, parallel array classes using expression templates
Boost spirit (有翻译的中文用户手册), The Spirit framework enables a target grammar to be written exclusively in C++. Inline EBNF grammar specifications can mix freely with other C++ code.
BLL (Boost Lambda Library)