在C ++中模板化一个'for'循环? [英] Template-ing a 'for' loop in C++?

查看:109
本文介绍了在C ++中模板化一个'for'循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++代码段,运行时用于循环,

I have a C++ snippet below with a run-time for loop,

for(int i = 0; i < I; i++)
  for (int j = 0; j < J; j++)
    A( row(i,j), column(i,j) ) = f(i,j);

重复调用该代码段。循环边界'I'和'J'在编译时是已知的(I / J是2到10的数量级)。我想使用模板展开循环。主要瓶颈是row()和column()和f()函数。我想用在编译时使用 row< i,j> :: enum 技巧来评估的等效元程序来替换它们。

The snippet is called repeatedly. The loop bounds 'I' and 'J' are known at compile time (I/J are the order of 2 to 10). I would like to unroll the loops somehow using templates. The main bottleneck is the row() and column() and f() functions. I would like to replace them with equivalent metaprograms that are evaluated at compile-time, using row<i,j>::enum tricks.

我真正喜欢的是最终将循环解析为一系列语句,如:

What I'd really love is something that eventually resolves the loop into a sequence of statements like:

A(12,37) = 0.5;
A(15,23) = 0.25;
A(14,45) = 0.25;

但我想这样做而不会破坏 for - 结构太多。本着以下精神:

But I'd like to do so without wrecking the for-for structure too much. Something in the spirit of:

TEMPLATE_FOR<i,0,I>
  TEMPLATE_FOR<j,0,J>
     A( row<i,j>::value, column<i,j>::value ) = f<i,j>::value

可以boost :: lambda(或其他)帮助我创建这个?

Can boost::lambda (or something else) help me create this?

推荐答案

一个好的编译器应该为你展开。例如,在使用-O2选项的gcc编译中,打开循环展开。

A good compiler should do unrolling for you. For instance, in gcc compiling with the -O2 option turns on loop unrolling.

如果您尝试手动执行此操作,除非仔细测量并真正知道您正在做什么,否则您最终可能会遇到更慢的代码。例如,在手动展开的情况下,您可能会阻止编译器执行循环互换或带状区域优化(在 gcc文档

If you try to do it yourself manually, unless you measure things carefully and really know what you are doing, you are liable to end up with slower code. For example, in your case with manual unrolling you are liable to prevent the compiler from being able to do a loop interchange or stripmine optimization (look for --floop-interchange and -floop-strip-mine in the gcc docs)

这篇关于在C ++中模板化一个'for'循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆