Unroll loop at compile time

旧城冷巷雨未停 提交于 2019-12-02 12:09:57

问题


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{ ... }

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.

I could write out the whole thing:

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();

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.

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); }

回答1:


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;
}

And the output of this example is :

0
1
2
3
4



回答2:


Provided your loop threshold is known at compile time, this is uber easy:

template<class CB, size_t... Is> void unroll_loop_impl(std::index_sequence<Is...> {}, CB&& cb) {
    void* aux[] = {(cb(Is), nullptr)...};
    (void)aux;
}


template<size_t N, class CB> void unroll_loop(CB&& cb) {
     using index_seqeunce_t = std::make_index_sequence<N>;

     unroll_loop_impl(std::move(cb), index_sequence_t{});
}


来源:https://stackoverflow.com/questions/45758545/unroll-loop-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!