为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态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;

为什么除了枚举值以表示相同值之外,为什么还要使用静态常量?为什么我们不能只使用枚举值?在这种情况下,考虑到这些是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。一种非常有用的技术,它使代码维护更加容易,尽管它增加了代码大小。

最新更新