6 c++ templates loop-unrolling
维基百科(这里)给出了一个编译时间展开for循环.......我想知道我们可以使用类似的for循环内部的模板语句...例如......
以下循环有效
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
...
}
}
Run Code Online (Sandbox Code Playgroud)
SubDomain是一个接受模板参数int的类,这里使用一个参数构造,该参数是Device类的成员.
谢谢你的回答...现在你知道我想要什么......无论如何,我实现了我想要的?
我终于得到了我想要的..............而不是直接使用for循环......我可以使用Boost :: MPL for_each构造.我还没有实现它,但我猜这提供了一种方法来做我想要的.....
我在这里从另一个堆栈溢出问题中得到了答案...但是对同一个问题的评论谴责它的使用,因为它会非常慢(当然对于大的循环)...但是...对于不大的循环我不要认为应该有任何膨胀...我会尝试代码,让你知道结果....
在该示例中很好地说明了该用途
对此有一个标准的解决方案.将迭代转换为递归.
template<int i>
void Device::createSubDomains()
{
SubDomain<i> tmp(member);
// some operations on tmp
createSubDomains<i-1>();
}
template<>
void Device<-1>::createSubDomains()
{
// End of recursion.
}
Run Code Online (Sandbox Code Playgroud)
注意:您不能使用运行时if(i!=0) createSubDomains<i-1>();.
2017注意:您现在可以使用编译时 if constexpr(i!=0) createSubDomains<i-1>();