编译期间求值,将计算提前到编译期间进行,可以最大限度地榨干编译器的潜力,提高程序的运行速度,用Andrei Alexanderescu的话说就是“时间花在编译期,就某种意义来说这是‘免费的’”(《C++设计新思维》P55)。所以就有了对数组在编译期间求和的需求。
先上代码,再解释:
#include <iostream>
using namespace std;
//一个全局的int数组,需要对其求和
const int CONST_ARRAY[5]={1,2,3,4,5};//去掉const属性后,编译也可以通过
//一个类模板,用于对数组求和
template<int index>
struct SumArrInCompilePhaseCls{
static const int SUM;
};
//通过递归定义模板的方式求SUM的值
template<int index>
const int SumArrInCompilePhaseCls<index>::SUM
=CONST_ARRAY[index]+SumArrInCompilePhaseCls<index-1>::SUM;//亮点在这里
//一个完全特化的类模板,用于结束模板的递归定义
template<>
struct SumArrInCompilePhaseCls<0>{
static const int SUM;
};
const int SumArrInCompilePhaseCls<0>::SUM=CONST_ARRAY[0];
int main(){
//使用模板,进行编译期间的数组求和
cout<<SumArrInCompilePhaseCls<4>::SUM<<endl;//结果15
}
SUM确实是在编译阶段计算的&#