c++ - 为什么 Fmtflags 被指定两次 - 一次作为枚举的一部分,另一个实例作为静态 const 变量
问题描述
在 STD 库文件 ios_base.h 中,我们看到以下内容:
enum _Ios_Fmtflags
{
_S_boolalpha = 1L << 0,
_S_dec = 1L << 1,
_S_fixed = 1L << 2,
_S_hex = 1L << 3,
_S_internal = 1L << 4,
_S_left = 1L << 5,
_S_oct = 1L << 6,
_S_right = 1L << 7,
_S_scientific = 1L << 8,
_S_showbase = 1L << 9,
_S_showpoint = 1L << 10,
_S_showpos = 1L << 11,
_S_skipws = 1L << 12,
_S_unitbuf = 1L << 13,
_S_uppercase = 1L << 14,
_S_adjustfield = _S_left | _S_right | _S_internal,
_S_basefield = _S_dec | _S_oct | _S_hex,
_S_floatfield = _S_scientific | _S_fixed,
_S_ios_fmtflags_end = 1L << 16
};
但在那之后我们也看到:
/// Insert/extract @c bool in alphabetic rather than numeric format.
static const fmtflags boolalpha = _S_boolalpha;
/// Converts integer input or generates integer output in decimal base.
static const fmtflags dec = _S_dec;
/// Generate floating-point output in fixed-point notation.
static const fmtflags fixed = _S_fixed;
/// Converts integer input or generates integer output in hexadecimal base.
static const fmtflags hex = _S_hex;
为什么除了枚举值之外,他们还使用 static const 来表示相同的值?为什么我们不能只使用枚举值?考虑到这些是 const 值,在这种情况下使用静态不是浪费吗?
谢谢, 奥弗
解决方案
目标是分离接口和实现。_Ios_Fmtflags
是实现定义的并且可以在将来更改,ios_base
不应该显着依赖_Ios_Fmtflags
,但必须提供一组常量作为文档接口的一部分,请参阅注释。我们如何避免代码对内部_Ios_Fmtflags
实现的依赖?我们可以_Ios_Fmtflags
对这种类型的类型和常量对象使用同义词,这将进一步完成:
typedef _Ios_Fmtflags fmtflags;
static const fmtflags boolalpha = _S_boolalpha;
static const fmtflags dec = _S_dec;
现在只有这些行取决于具体的 _Ios_Fmtflags
实现。例如,我们可以重命名_S_boolalpha
,它不会影响代码,除了一行static const fmtflags boolalpha = _S_boolalpha;
或者另一个例子,我们可以用enum _Ios_Fmtflags
整数或其他合适的类型替换。一种非常有用的技术,它使代码维护变得更加容易,尽管它增加了代码大小。
推荐阅读
- yaml - YAML 中的锚点和别名是存储字符串还是内插字符串?
- pine-script - 如何防止启用 calc_on_every_tick 时由于触发过多而导致交易视图停止警报
- r - 问题制作清单
- reactjs - 如何动态导入作为json数据的反应模块
- swift - 系统网络扩展通过 OpenVPN 协议连接到 VPN,但无法查看任何网页
- excel - 命名表头时出现类型不匹配错误
- android - 从 Set > clusters获取 CustomClusterItem
- google-api - 获取 google 环聊会议中的列表或人员
- c - 使用动态内存分配的程序
- android - 添加启动画面时,Android 模拟器不会加载