官术网_书友最值得收藏!

Using scoped enumerations

Enumeration is a basic type in C++ that defines a collection of values, always of an integral underlying type. Their named values, which are constant, are called enumerators. Enumerations declared with the keyword enum are called unscoped enumerations, while enumerations declared with enum class or enum struct are called scoped enumerations. The latter ones were introduced in C++11 and are intended to solve several problems with unscoped enumerations, which are explained in this recipe.

How to do it...

When working with enumerations, you should:

  • Prefer to use scoped enumerations instead of unscoped ones
  • Declare scoped enumerations using enum class or enum struct:
    enum class Status { Unknown, Created, Connected };
    Status s = Status::Created;
    

    The enum class and enum struct declarations are equivalent, and throughout this recipe and the rest of this book, we will use enum class.

Because scope enumerations are restricted namespaces, the C++20 standard allows us to associate them with a using directive. You can do the following:

  • Introduce a scoped enumeration identifier in the local scope with a using directive, as follows:
    int main()
    {
      using Status::Unknown;
      Status s = Unknown;
    }
    
  • Introduce all the identifiers of a scoped enumeration in the local scope with a using directive, as follows:
    struct foo
    {
      enum class Status { Unknown, Created, Connected };
      using enum Status;
    };
    foo::Status s = foo::Created; // instead of
     // foo::Status::Created
    
  • Use a using enum directive to introduce the enum identifiers in a switch statement to simplify your code:
    void process(Status const s)
    {
      switch (s)
      {
        using enum Status;
        case Unknown:   /*...*/ break;
        case Created:   /*...*/ break;
        case Connected: /*...*/ break;
      }
    }
    

How it works...

Unscoped enumerations have several issues that create problems for developers:

  • They export their enumerators to the surrounding scope (for which reason, they are called unscoped enumerations), and that has the following two drawbacks:
    1. It can lead to name clashes if two enumerations in the same namespace have enumerators with the same name, and
    2. It's not possible to use an enumerator using its fully qualified name:
      enum Status {Unknown, Created, Connected};
      enum Codes {OK, Failure, Unknown};   // error
      auto status = Status::Created;       // error
      
  • Prior to C++ 11, they could not specify the underlying type, which is required to be an integral type. This type must not be larger than int, unless the enumerator value cannot fit a signed or unsigned integer. Owing to this, forward declaration of enumerations was not possible. The reason for this was that the size of the enumeration was not known. This was because the underlying type was not known until the values of the enumerators were defined so that the compiler could pick the appropriate integer type. This has been fixed in C++11.
  • Values of enumerators implicitly convert to int. This means you can intentionally or accidentally mix enumerations that have a certain meaning and integers (which may not even be related to the meaning of the enumeration) and the compiler will not be able to warn you:
    enum Codes { OK, Failure };
    void include_offset(int pixels) {/*...*/}
    include_offset(Failure);
    

The scoped enumerations are basically strongly typed enumerations that behave differently than the unscoped enumerations:

  • They do not export their enumerators to the surrounding scope. The two enumerations shown earlier would change to the following, no longer generating a name collision and being possible to fully qualify the names of the enumerators:
    enum class Status { Unknown, Created, Connected };
    enum class Codes { OK, Failure, Unknown }; // OK
    Codes code = Codes::Unknown;               // OK
    
  • You can specify the underlying type. The same rules for underlying types of unscoped enumerations apply to scoped enumerations too, except that the user can explicitly specify the underlying type. This also solves the problem with forward declarations since the underlying type can be known before the definition is available:
    enum class Codes : unsigned int;
    void print_code(Codes const code) {}
    enum class Codes : unsigned int
    {
      OK = 0,
      Failure = 1,
      Unknown = 0xFFFF0000U
    };
    
  • Values of scoped enumerations no longer convert implicitly to int. Assigning the value of an enum class to an integer variable would trigger a compiler error unless an explicit cast is specified:
    Codes c1 = Codes::OK;                       // OK
    int c2 = Codes::Failure;                    // error
    int c3 = static_cast<int>(Codes::Failure);  // OK
    

However, the scoped enumerations have a drawback: they are restricted namespaces. They do not export the identifiers in the outer scope, which can be inconvenient at times. For instance, if you are writing a switch and you need to repeat the enumeration name for each case label, as in the following example:

std::string_view to_string(Status const s)
{
  switch (s)
  {
    case Status::Unknown:   return "Unknown";
    case Status::Created:   return "Created";
    case Status::Connected: return "Connected";
  }
}

In C++20, this can be simplified with the help of a using directive with the name of the scoped enumeration. The preceding code can be simplified as follows:

std::string_view to_string(Status const s)
{
  switch (s)
  {
    using enum Status;
    case Unknown:   return "Unknown";
    case Created:   return "Created";
    case Connected: return "Connected";
  }
}

The effect of this using directive is that all the enumerator identifiers are introduced in the local scope, making it possible to refer to them with the unqualified form. It is also possible to bring only a particular enum identifier to the local scope with a using directive with the qualified identifier name, such as using Status::Connected.

See also

  • Creating compile-time constant expressions in Chapter 9, Robustness and Performance to learn how to work with compile-time constants
主站蜘蛛池模板: 怀来县| 固原市| 余庆县| 亚东县| 齐河县| 文山县| 平山县| 静安区| 高密市| 博罗县| 信阳市| 渝中区| 舒兰市| 宁强县| 志丹县| 奈曼旗| 泊头市| 改则县| 上杭县| 玉环县| 无为县| 临城县| 潞城市| 延庆县| 日喀则市| 宜宾县| 南江县| 文成县| 安阳市| 常熟市| 治多县| 金溪县| 东方市| 哈密市| 开鲁县| 上饶县| 陆川县| 镇雄县| 吉林省| 高青县| 乌苏市|