问题
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
回答1:
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>.
回答2:
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.
回答3:
thank you guys.
dr Hirsch is the closest to what is needed, but in the end the predecessor solution is the cleanest. Let me restate the problem: several templates needed to be instantiated at compile time using constant parameters
f0 = f<0,0>();
f1 = f<0,1>();
...
fk = f<m,n>();
for any significant number of m, and n unrolling template creation makes code busy. With boost preprocessor i have done the following:
#include "boost/preprocessor/seq/for_each_product.hpp"
#include "boost/preprocessor/seq/to_tuple.hpp"
#define SEQ_MASK (0x1)(0x3)
#define SEQ_M (1)(2)
#define SEQ_N (1)(2)
#define INSTANCE(r, tparams) { \
Kernel kernel = Instance<BOOST_PP_SEQ_ENUM(tparams)>(); \
kernels[kernel.key()] = kernel; }
BOOST_PP_SEQ_FOR_EACH_PRODUCT(INSTANCE, (SEQ_MASK)(SEQ_M)(SEQ_N));
after preprocessor runs, it produces all combinations of three sequences defined.
回答4:
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.
回答5:
Templates are instantiated at compile time, not run time, so you can't instantiate them in a loop at all.
来源:https://stackoverflow.com/questions/1774882/c-instantiate-templates-in-loop