Search code examples
c++templatesloop-unrolling

template arguments inside a compile time unrolled for loop?


wikipedia (here) gives a compile time unrolling of for loop....... i was wondering can we use a similar for loop with template statements inside... for example...

is the following loop valid

template<int max_subdomain>
void Device<max_sudomain>::createSubDomains()
{
    for(int i=0; i< max_subdomain; ++i)
    {
        SubDomain<i> tmp(member);
        ...
        // some operations on tmp
        ...
    }
}

SubDomain is a class which takes in the a template parameter int and here has been constructed with an argument that is a member of the Device class.

Thanks for the answer guys... now that you know what i want... is there anyway i achieve what i want to??

i finally got what i wanted.............. instead of using the for loop directly... one can instead use the Boost::MPL for_each construct. I haven't yet implemented it but I am guessing that this provides a way to do what i wanted.....

I took the answer from another stack overflow question here... However the comment to the same question decries its use because it would be very slow (for large for loops of course)... however.. for loops which are not large i don't think there should be any bloating... i'll try the code and let you know the results....

the use is illustrated well in the example


Solution

  • Re-Edit:

    My previous answer was correct. I have tried your code, it's giving compiler error. You cannot declare objects like that, as i cannot remain a compile time constant (as you are intending to do i++). template parameter must always be compile time constants. Here is the demo.

    Also note that, loop unrolling is done for normal loops also, as part of optimization by compilers. It's not limited to templates.