为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态const变量
Why Fmtflags are specified twice - once as part of an enum, and another instance as a static const variable
在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;
为什么除了枚举值以表示相同值之外,为什么还要使用静态常量?为什么我们不能只使用枚举值?在这种情况下,考虑到这些是const值吗?
在这种情况下,使用静态浪费吗?谢谢Ofer
目标是分开接口和实现。_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;
或作为另一个示例,我们可以用Integer或其他一些合适的类型替换enum _Ios_Fmtflags
。一种非常有用的技术,它使代码维护更加容易,尽管它增加了代码大小。
相关文章:
- 不带大括号的枚举形式
- 枚举环境变量的惯用C++14/C++17方法
- 类似枚举的计算常量
- 如何正确实现和访问运算符的各种自定义枚举器
- 错误:从"int"到枚举c++的转换无效
- C++中构造函数中的枚举
- 访问在 C++ 结构中声明的枚举变量
- 枚举类'classname'的多重定义
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- typedef 枚举和枚举类有什么区别?
- 为什么我的开关/机箱在使用枚举时默认?
- 标准::可选枚举的比较运算符
- C++两个源文件之间共享的枚举的静态实例
- 打印没有铸件的枚举可以在C++中吗?
- 枚举成员与静态 int 成员?
- C++:枚举:错误:应使用标识符而不是"}"
- 带有 c++ 的枚举(输入检查)
- 在 qml 中使用 Q_ENUM 和 Q_PROPERTY 作为枚举类
- 为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态const变量
- 如何使用枚举类值作为 for 循环的一部分