C++ 表达式模板

2021-12-13 00:00:00 c expression templates c++

我目前使用 C 语言进行数值计算.我听说使用 C++ 表达式模板更适合科学计算.简单来说,什么是 C++ 表达式模板?

I currently use C for numerical computations. I've heard that using C++ Expression Templates is better for scientific computing. What are C++ Expression Templates in simple terms?

  1. 是否有关于使用 C++ 表达式模板讨论数值方法/计算的书籍?

  1. Are there books around that discuss numerical methods/computations using C++ Expression Templates?

在哪些方面,C++ 表达式模板比使用纯 C 更好?

In what way, C++ Expression Templates are better than using pure C?

推荐答案

简单来说什么是 C++ 表达式模板?

What are C++ Expression Templates in simple terms?

表达式模板 是一类 C++ 模板元编程,它延迟子表达式的计算直到完整表达式是已知的,因此可以应用优化(尤其是消除临时变量).

Expression templates are a category of C++ template meta programming which delays evaluation of subexpressions until the full expression is known, so that optimizations (especially the elimination of temporaries) can be applied.

是否有关于使用 C++ 表达式模板讨论数值方法/计算的书籍?

Are there books around that discuss numerical methods/computations using C++ Expression Templates?

我相信 ET 是由 Todd Veldhuizen 发明的,他在 15 年前发表了一篇关于它的论文.(似乎许多旧链接现在已经失效,但目前 here 是它的一个版本.)有关它的一些材料在 David Vandevoorde 和 Nicolai Josuttis 的 C++ 模板:完整指南.

I believe ET's were invented by Todd Veldhuizen who published a paper on it 15 years ago. (It seems that many older links to it are dead by now, but currently here is a version of it.) Some material about it is in David Vandevoorde's and Nicolai Josuttis' C++ Templates: The Complete Guide.

C++ 表达式模板在哪些方面比使用纯 C 更好?

In what way, C++ Expression Templates are better than using pure C?

它们允许您以富有表现力的高级方式编写代码而不会损失性能.例如,

They allow you to write your code in an expressive high level way without losing performance. For example,

void f(const my_array<double> a1, const my_array<double> a2) 
{ 
  my_array<double> a3 = 1.2 * a1 + a1 * a2; 
  // ..
}

可以一直优化到

for( my_array<double>::size_type idx=0; idx<a1.size(); ++idx ) 
  a3[idx] = 1.2*a1[idx] + a1[idx]*a2[idx]; 

这更快,但更难理解.

相关文章