Effective C++ Item2: Enum hack
来源:互联网 发布:遥感大数据的特点 编辑:程序博客网 时间:2024/06/18 05:22
从一个例子开始吧
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 了。
使用enum hack的技巧,其思想就是把GameTurn定义为一个枚举常量。上面的代码可以写为:
class Game {private: // static const int GameTurn; enum {GameTurn = 10}; //no named enum class. 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是模板元编程的一项基本技术,大量的代码在使用它。当你看到它时,你要认识它。
阅读全文
0 0
- Effective C++ Item2: Enum hack
- 重读经典-《Effective C++》Item2:尽量以const,enum,inline替换#define
- 重读经典-《Effective C++》Item2:尽量以const,enum,inline替换#define
- 重读经典-《Effective C++》Item2:尽量以const,enum,inline替换#define
- 重读经典-《Effective C++》Item2:尽量以const,enum,inline替换#define
- Effective C++ Item2
- enum hack
- Effective Objective-C Item2: 头文件中最少引入其他头文件
- the enum hack
- C++的Enum hack
- enum hack用法
- C++的Enum hack
- Effective Modern C++翻译系列之Item2
- iTem2
- Item2: Prefer C++-style casts
- 《Effective C++》尽量以const,enum,inline,替换#define
- effective C++:尽量以const、enum、inline替换#define
- item2: 尽量以const,enum,inline替换#define
- java定时任务之Timer实现多线程任务
- 后端 mapper里resultMap转换
- npm命令总结汇总
- python django url导入
- 【.Net码农】【淘宝API】淘宝API代码c#实例(摘)
- Effective C++ Item2: Enum hack
- 交互设计师为什么需要具备产品思维
- android camera2 拍照流程
- Lopoper 退出循环的原理
- 分布式系统中生成全局唯一ID的方法
- 前端 HTML空格
- js字符串转日期,日期转字符串
- HashMap与ArrayMap(和SparseArray)的比较与选择
- JAVA操作EXCEL