使用表达式模板的中间结果
C++ 模板元编程:Boost 及其他概念、工具和技术
... 表达式模板的一个缺点是它们往往鼓励编写大型、复杂的表达式,因为计算只会延迟到调用赋值运算符为止。如果程序员想要重用某些中间结果而不提前评估它,她可能会被迫声明一个复杂的类型,例如:
Expression<
Expression<Array,plus,Array>,
plus,
Expression<Array,minus,Array>
> intermediate = a + b + (c - d);
(或更糟)。请注意,这种类型不仅准确且冗余地反映了计算的结构,因此需要在公式更改时进行维护,而且还会淹没它?对于 C++ DSEL 来说,这是一个长期存在的问题。通常的解决方法是使用类型擦除来捕获表达式,但在这种情况下,需要为动态分派付费。最近,由 Bjarne Stroustrup 本人带头的关于重用残留的 auto 关键字在变量声明中进行类型推导的讨论很多,因此上面的内容可以重写为:
auto intermediate = a + b + (c - d);
此功能对于 C++ DSEL 作者和用户来说都是一个巨大的优势......
是否可以使用当前的 c++ std. (非 C++0X)
例如,我想编写一个表达式,如下所示:
Expr X,Y
矩阵 A,B,C,D
X=A+B+C
Y=X+C
D:=X+Y
其中运算符: = 在最晚时间计算表达式。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
目前,您始终可以使用 BOOST_AUTO () 代替 C++0x 的 auto 关键字,以便更轻松地获得中间结果。
For now, you can always use BOOST_AUTO() in the place of C++0x's auto keyword to get intermediate results more easily.
我不明白你的问题。
auto
将在C++0x
中重用于 自动类型推断。我个人认为这是表达式模板的一个缺点,因为它们通常依赖于比它们所构建的对象更小的生命周期,如果表达式模板被捕获,那么可能会被证明是错误的,正如我所解释的 此处。
I don't understand your question.
auto
is going to be reused inC++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.