为什么Fmtflags被指定两次 - 一次作为枚举的一部分,另一个实例作为静态const变量

问题描述 投票:1回答:1

在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来表示相同的值?为什么我们不能只使用枚举值?考虑到这些是const值,在这种情况下是不是使用静态浪费?

谢谢,优惠

c++ std
1个回答
1
投票

目标是分离界面和实现。 _Ios_Fmtflags是实现定义的,将来可以更改,ios_base不应该显着依赖于_Ios_Fmtflags,但必须提供一组常量作为记录的接口see comment的一部分。我们怎样才能避免对内部_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。虽然它增加了代码大小,但是使代码维护更容易的非常有用的技术。

© www.soinside.com 2019 - 2024. All rights reserved.