C ++实例化循环中的模板 [英] C++ instantiate templates in loop

查看:96
本文介绍了C ++实例化循环中的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工厂类,该类需要使用连续的模板参数(它们是简单的整数)实例化几个模板.如何在不展开整个循环的情况下实例化此类模板功能?

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?

谢谢

推荐答案

模板参数必须是编译时常量.当前,即使展开后,也没有编译器将循环计数器变量视为常量.这可能是因为必须在模板实例化过程中知道其常数性,而这种常数化在循环展开之前就已经发生了.

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;

将从循环< 10>到循环< 1>创建十个模板类.

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

这篇关于C ++实例化循环中的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆