编译时展开循环 [英] Unroll loop at compile time

查看:191
本文介绍了编译时展开循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以i = 0,1, ... , n的形式将许多行写入形式为foo(i)的C ++文件中,有没有办法在编译时做到这一点?

I want to write a load of lines into a C++ file of the form foo(i) for i = 0,1, ... , n, is there a way of doing this at compile time?

我想这样做是因为我有一个模板化的类:

I want to do this because I've got a templated class:

template <int X> class MyClass{ ... }

我想用类似这样的东西来测试它的许多不同的"X"值:

and I want to test it for lots of different values of "X" with something like:

for (int i = 0; i < n; i++) {
    MyClass<i> bar;
    bar.method()
 }

这不起作用,因为它希望在编译时确定作为模板值传递的值.

This doesn't work as it wants the value passed as the template value to be determined at compile time.

我可以写出全部内容:

MyClass<0> bar0; bar0.method();
MyClass<1> bar1; bar1.method();

我可以定义一个定义来加快它的速度,例如:

and I could make a define to speed it up a bit, something like:

#define myMacro(x) MyClass<x> bar_x; bar_x.method();

,但是我仍然不得不在任何地方写myMacro,并且我想太频繁地更改范围以使其明智.如果我可以编写某种形式的for循环的宏版本,那么可以节省很多时间.

but I'd still have to write myMacro everywhere and I'm going to want to change the range too often for this to be sensible. If I could write some sort of macro version of a for loop it'd save me a lot of time.

更新:我实际上需要将变量传递给我的方法,因此我对@Pascal给出的可接受答案做了些微改动

Update: I actually needed to pass variables to my method so I made slight changes to the accepted answer given by @Pascal

template<int X> class MyClass { public: void foo(int Y) { std::cout << X Y<< std::endl; } };
template<int X> inline void MyTest(int Y) { MyTest<X - 1>(Y); MyClass<X-1> bar; bar.foo(Y); }
template<> inline void MyTest<1>(int Y) { MyClass<0> bar; bar.foo(Y); }

推荐答案

更接近宏方法"的解决方案可以是模板递归:

A solution closer to the "macro way" can be the template recursivity :

template<int X> class MyClass { public: void foo() { std::cout << X << std::endl; } };
template<int X> inline void MyTest() { MyTest<X - 1>(); MyClass<X-1> bar; bar.foo(); }
template<> inline void MyTest<1>() { MyClass<0> bar; bar.foo(); }
int main()
{
    MyTest<5>();
    return 0;
}

此示例的输出为:

0
1
2
3
4

这篇关于编译时展开循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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