简体   繁体   中英

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

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

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.

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.

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.

模板在编译时实例化,而不是在运行时实例化,因此您根本无法在循环中实例化它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM