1.定义:
运行在编译期间的代码,执行速度快于正常c++代码,但是会延长编译期的时间。
优点:
- 较小的可执行文件
- 较短的运行期
- 较少的内存需求(运用的enum不开辟空间)
2.最基础的模板元程序
计算n!
template<unsigned n>
class Func {
public:
enum { re = Func<n - 1>::re * n };
//static const int re = Func<n - 1>::re * n;
};
template<>
class Func<1> {
public:
enum{re=1};
//static const int re = 1;
};
为什么推荐用enum,而不是static const?运行编译都可以通过。
The main reason was that compilers were unable to deal with static const integers (including
bool). The advantage of using an enum over a static constant is that the compiler will never reserve
storage space for the constant, as the computation is either static or it fails.
Conversely, a static constant integer could be “misused” as a normal integer, for example, taking
its address (an operation that the compiler will disallow on enums).
enum不会开辟空间、没有地址,值不会被改变,而static const int 会。
To be continue