内容: 记录C++中对于在编译器就可以求出值的情况会优先在编译期间求值
代码如下:
#include <iostream>
using namespace std;
template <int n>
struct add {
static const int value = n * add< n - 1 >::value;
};
template <>
struct add< 0 > {
static const int value = 1;
};
int main() {
printf("the value is : %d\n",add<5>::value);
return 0;
}
查看汇编结果:使用g++的-s
结果分析:
C++中对于常数表达式,或者是模板特化的使用会直接在编译期间优化成结果。所以可以看到直接计算
5!的结果120。而不是递归的进行运算