Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ instantiate templates in loop

I have have a factory class, which needs to instantiate several templates with consecutive template parameters which are simple integers. How can I instantiate such template functions without unrolling the entire loop?

The only thing that can think of is using boost pre-processor. Can you recommend something else, which does not depend on the preprocessor?

thanks

like image 339
Anycorn Avatar asked Nov 21 '09 07:11

Anycorn


2 Answers

Template parameters have to be compile-time constant. Currently no compiler considers a loop counter variable to be a constant, even after it is unrolled. This is probably because the constness has to be known during template instantation, which happens far before loop unrolling.

But it is possible to construct a "recursive" template and with a specialization as end condition. But even then the loop boundary needs to be compile time constant.

template<int i>
class loop {
    loop<i-1> x;
}

template<>
class loop<1> {
}

loop<10> l;

will create ten template classes from loop<10> to loop<1>.

like image 130
Gunther Piez Avatar answered Oct 07 '22 04:10

Gunther Piez


It probably could be done using the Boost metaprogramming library. But if you haven't used it before or are used to do excessive template programming it probably won't be worth the amount of work it would need to learn how to do it.

like image 37
sth Avatar answered Oct 07 '22 04:10

sth