编译时内的模板参数展开 for 循环? [英] template arguments inside a compile time unrolled for loop?

查看:31
本文介绍了编译时内的模板参数展开 for 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

维基百科(此处)给出了 for 循环的编译时展开.......我想知道我们可以在内部使用带有模板语句的类似 for 循环吗...例如...

wikipedia (here) gives a compile time unrolling of for loop....... i was wondering can we use a similar for loop with template statements inside... for example...

以下循环是否有效

template<int max_subdomain>
void Device<max_sudomain>::createSubDomains()
{
    for(int i=0; i< max_subdomain; ++i)
    {
        SubDomain<i> tmp(member);
        ...
        // some operations on tmp
        ...
    }
}

SubDomain 是一个类,它接受模板参数 int 并且这里已经用一个作为 Device 类成员的参数构造.

SubDomain is a class which takes in the a template parameter int and here has been constructed with an argument that is a member of the Device class.

谢谢大家的回答...既然你知道我想要什么...无论如何,我有没有达到我想要的?

Thanks for the answer guys... now that you know what i want... is there anyway i achieve what i want to??

我终于得到了我想要的......................而不是直接使用 for 循环...可以改为使用 Boost::MPL for_each 构造.我还没有实现它,但我猜这提供了一种方法来做我想做的......

i finally got what i wanted.............. instead of using the for loop directly... one can instead use the Boost::MPL for_each construct. I haven't yet implemented it but I am guessing that this provides a way to do what i wanted.....

我从另一个堆栈溢出问题这里中得到了答案... 然而,对同一问题的评论谴责它的使用是因为它会很慢(当然对于大的 for 循环)......但是......对于不是很大的循环我认为不应该有任何膨胀......我会尝试代码并让你知道结果....

I took the answer from another stack overflow question here... However the comment to the same question decries its use because it would be very slow (for large for loops of course)... however.. for loops which are not large i don't think there should be any bloating... i'll try the code and let you know the results....

例子

推荐答案

重新编辑:

我之前的回答是正确的.我试过你的代码,它给出了编译器错误.您不能像这样声明对象,因为 i 不能保持编译时常量(正如您打算做的那样 i++).template 参数必须始终是编译时常量.这是演示.

My previous answer was correct. I have tried your code, it's giving compiler error. You cannot declare objects like that, as i cannot remain a compile time constant (as you are intending to do i++). template parameter must always be compile time constants. Here is the demo.

另请注意,循环展开也适用于普通循环,作为编译器优化的一部分.不限于templates.

Also note that, loop unrolling is done for normal loops also, as part of optimization by compilers. It's not limited to templates.

这篇关于编译时内的模板参数展开 for 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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