编译时递归的工作原理? [英] How compile time recursion works?
问题描述
我在这里找到了一个代码在没有循环或条件的情况下打印1到1000
I found a code here Printing 1 to 1000 without loop or conditionals
有人可以解释编译时递归的工作原理,无法在google中找到它
Can someone please explain how compile time recursion works, couldn't find it in google
// compile time recursion
template<int N> void f1()
{
f1<N-1>();
cout << N << '\n';
}
template<> void f1<1>()
{
cout << 1 << '\n';
}
int main()
{
f1<1000>();
}
谢谢!
推荐答案
它反复实例化 f1< N>
模板,其中 N
( f1< N>()
调用 f1< N-1>
等)。 N == 1
的显式专门化结束了递归:只要 N
变为1,编译器将选择
It repeatedly instantiates the f1<N>
template with decreasing values for N
(f1<N>()
calls f1<N-1>
and so on). The explicit specialization for N==1
ends the recursion: as soon as N
becomes 1, the compiler will pick the specialized function rather than the templated one.
f1< 1000>()
会导致编译器实例化 f1< / code> 999次(在对
f1
的最终调用中不计算)。这就是为什么它需要一段时间来编译代码,大量使用模板元编程技术的原因。
f1<1000>()
causes the compiler to instantiate f1<N>
999 times (not counting in the final call to f1<1>
). This is the reason why it can take a while to compile code that makes heavy use of template meta-programming techniques.
整个事件很大程度上依赖于编译器的优化技巧 - 理想情况下,它应该完全删除递归(其仅作为使用模板来模拟循环的黑客)。
The whole thing relies heavily on the compiler's optimization skills - ideally, it should remove the recursion (which only serves as hack to emulate a for
loop using templates) completely.
这篇关于编译时递归的工作原理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!