views:

337

answers:

5

hi

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

A: 

I do not think it's possible in run-time, because MyClass<1> and MyClass<2> are absolute different classes.

But I have one idea: if you know all possible values than you can write a switch in your factory class and pass this integer as a parameter into the factory.

Elalfer
If you use the switch way, then all classes will be instantiated. No way to only instantiate the one that equals `n` (because of course its value is not known at compile time).
Johannes Schaub - litb
+2  A: 

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.

sth
+6  A: 

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

drhirsch
A: 

Templates are instantiated at compile time, not run time, so you can't instantiate them in a loop at all.

Clifford
You can do loops/iteration with the compiler. See @drhirsch answer above.
Marcus Lindblom
I agree that drhirsch has provided a solution, but it is not a loop but a recursion, so my point stands. The point I was trying to emphasise was that templates are not instantiated at run-time, which in some sense serves as explanation of drhirsch's answer.
Clifford
+1  A: 
aaa