从一个例子开始吧编程
class Game { private: static const int GameTurn = 10; int scores[GameTurn]; };
对于支持类内初始化的C++编译器,这段代码能够编译经过。数组
可是较老的C++编译器,可能不支持类内初始化,这样咱们的静态常量,必需要在类外初始化。以下:编码
class Game { private: static const int GameTurn; int scores[GameTurn]; }; const int Game::GameTurn = 10;
若是没有int scores[GameTurn];
,这段代码就能够用不支持类内初始化的编译器经过了。指针
但由于 int scores[GameTurn];
用到了GameTurn
,而GameTurn
的值不能肯定。因此会报以下错误。调试
enum_hack.cpp:5: error: array bound is not an integer constant
这种状况下,若是咱们仍然不想用硬编码的数字指定数组的大小,就能够考虑这篇文章的主角: enum hack
了。code
使用enum hack
的技巧,其思想就是把GameTurn
定义为一个枚举常量。上面的代码能够写为:内存
class Game { private: // static const int GameTurn; enum {GameTurn = 10}; int scores[GameTurn]; }; // const int Game::GameTurn = 10;
这样代码就能够编译经过了。字符串
《Effective C++》中这样描述enum hack
的好处:编译器
enum hack
的行为更像#define
而不是const
,若是你不但愿别人获得你的常量成员的指针或引用,你能够用enum hack
替代之。(为何不直接用#define
呢?首先,由于#define
是字符串替换,因此不利于程序调试。其次,#define
的可视范围难以控制,好比你怎么让#define
定义的常量只在一个类内可见呢?除非你用丑陋的#undef
。编译
使用enum hack
不会致使 “没必要要的内存分配”。
enum hack
是模板元编程的一项基本技术,大量的代码在使用它。当你看到它时,你要认识它。