前面enum一节介绍的是和template联合,引发编译器递归的奇妙作用。template本身无需enum配合也可以达到递归的效果。
// test template recursive for loop unrolling
cout << "test 2: template recursive for loop unrolling" << endl;
for (size_t i = 0; i < 8; ++i) {
cout << i;
}
cout << endl;
Loop<8>::Run();
cout << endl;
输出结果是:
test 2: template recursive for loop unrolling 01234567 01234567
为了达到上面的模拟for循环效果,需要定义一个Loop类:
template<int N>
class Loop {
public:
static inline int Run() {
int v = Loop<N - 1>::Run();
cout << v;
return v + 1;
}
};
template<>
class Loop<0> {
public:
static inline int Run() {
return 0;
}
};
这里演示了for循环展开的方式,因为在编译后的代码中是没有递归和循环的。有的是很多特化类Loop<8>, Loop<7>… Loop<0> 都执行了Run()方法。类似下面的执行代码:
Loop<8>::Run(); Loop<7>::Run(); Loop<6>::Run(); ... Loop<0>::Run();
原文:http://blog.csdn.net/csfreebird/article/details/44888785