Evgenii Legotckoi
Sept. 2, 2017, 5:25 p.m.

C++ - Tutorial 008. Enumerations

In addition to classes, C ++ supports enumerations. In the current standard, C ++ is supported as enumeration without the scope that was introduced in earlier versions of C ++, as well as C.

enum ColorTypes {
    Green,
    Yellow,
    Red
};

So enumerations with scope

enum class ColorTypes {
    Green,
    Yellow,
    Red
};

The difference between enumerations and scope from enumeration without scope

The difference between an enumeration and a scope is different from an enumeration without scope in that the enumeration variables with the scope can not be implicitly converted to integer variables and vice versa. For this conversion, use static_cast () .

enum class ColorTypes { Green, Yellow, Red };

ColorTypes currentType_1 = ColorTypes::Green; // Ok
ColorTypes currentType_2 = 2; // Error, conversion is impossible
int currentType_3 = ColorTypes::Red; // Error, conversion is impossible
int currentType_4 = Red; // Error, Red does not exist in this scope
int currentType_5 = static_cast<int>(ColorTypes::Green);

Such scope control allows you to declare enums in the class whose members have the same names. Also provides more control over the code, although it imposes a number of limitations.

How to Set Enumeration Values

By default, the enumeration starts at 0, and the enumeration of the members of the enumeration continues ...

enum class ColorTypes {
    Green,      // 0
    Yellow,     // 1
    Red,        // 2
    Black,      // 3
    Blue        // 4
};

but you can set your own values for enumerations when you declare.

enum class ColorTypes {
    Green = 15,                 // 15
    Yellow,                     // 16
    Red = 24,                   // 24
    Black = ColorTypes::Red,    // 24
    Blue                        // 25
};

Using switch case for enumerations

Enumerations with both scope and scope are supported by the condition and branch operators switch / case :

ColorTypes currentType = ColorTypes::Green;

switch (currentType)
{
    case ColorTypes::Green: std::cout << "Green"; break;
    case ColorTypes::Yellow: std::cout << "Yellow"; break;
    case ColorTypes::Black: std::cout << "Black"; break;
    case ColorTypes::Blue: std::cout << "Blue"; break;
    default: std::cout << "Unknown Type"; break;
}

If you talk about control of code execution and imposed restrictions when using enumerations with scope and without scope, you can simulate the situation when in switch / case for some reason (typo, copy-paste, noob, screwed up when resolving conflicts with the merge of branches) There are enumerations of different types. Then enumerations without scope are implicitly converted to the required type by the compiler and the code is executed, although it will be erroneous, and in the case of enumerations, the compiler will report an error and stop building the program.

That is, below, the following code, being erroneous, will be compiled:

enum SideTypes {
    Top,
    Bottom,
    Right,
    Left
};

enum ColorTypes {
    Green = 8,
    Yellow,
    Red,
    Blue
};

int main(int argc, char *argv[])
{
    ColorTypes currentType = ColorTypes::Green;

    switch (currentType)
    {
        case SideTypes::Top: std::cout << "Top Side"; break;
        case ColorTypes::Green: std::cout << "Green"; break;
        case ColorTypes::Yellow: std::cout << "Yellow"; break;
        case ColorTypes::Red: std::cout << "Red"; break;
        case ColorTypes::Blue: std::cout << "Blue"; break;
        default: std::cout << "Unknown Type"; break;
    }

    return 0;
}

At best, the compiler will throw Warning.

warning: case value ‘0’ not in enumerated type ‘ColorTypes’ [-Wswitch]
         case SideTypes::Top: std::cout << "Top Side"; break;
         ^

But sometimes it happens that the programmer "knows the C ++ better than the compiler" and disables warnings.

While the following code is simply not compiled:

enum class SideTypes {
    Top,
    Bottom,
    Right,
    Left
};

enum class ColorTypes {
    Green = 8,
    Yellow,
    Red,
    Blue
};

int main(int argc, char *argv[])
{
    ColorTypes currentType = ColorTypes::Green;

    switch (currentType)
    {
        case SideTypes::Top: std::cout << "Top Side"; break;
        case ColorTypes::Green: std::cout << "Green"; break;
        case ColorTypes::Yellow: std::cout << "Yellow"; break;
        case ColorTypes::Red: std::cout << "Red"; break;
        case ColorTypes::Blue: std::cout << "Blue"; break;
        default: std::cout << "Unknown Type"; break;
    }
    return 0;
}

The compiler will generate a compilation error:

error: could not convert ‘Top’ from ‘SideTypes’ to ‘ColorTypes’
         case SideTypes::Top: std::cout << "Top Side"; break;
                         ^

How to specify a specific integer type for enumeration

Enumerations can also have a more specific type, which must be a specific integer type:

  • unsigned char;
  • char;
  • int;
  • long int;
  • etc.

This allows you to allocate a certain amount of memory to variables that have enumeration values. Perhaps this may be relevant for embedded development. Depending on the target platform, a certain amount of memory will be allocated.

enum class SideTypes : short int {
    Top,
    Bottom,
    Right,
    Left
};

Iterator for enumerations

And finally, we'll make an iterator for the enumerations, with which we can use the range-based loop .

#include <iostream>

enum class ColorTypes
{
    Blue,
    Red,
    Green,
    Purple,
    First=ColorTypes::Blue,   // participant of the enumerator for the first element
    Last=ColorTypes::Purple // participant of the enumerator for the last item
};

ColorTypes operator++(ColorTypes& x)
{
    // std::underlying_type converts the type of ColorTypes into an integer type, under which the given enum was declared
    return x = static_cast<ColorTypes>(std::underlying_type<ColorTypes>::type(x) + 1);
}

ColorTypes operator*(ColorTypes c)
{
    return c;
}

ColorTypes begin(ColorTypes r)
{
    return ColorTypes::First;
}

ColorTypes end(ColorTypes r)
{
    ColorTypes l=ColorTypes::Last;
    return ++l;
}

int main(int argc, char *argv[])
{
    // We use parentheses to instantiate the enumeration
    for(const auto& c : ColorTypes())
    {
        std::cout << static_cast<int>(c) << std::endl;
    }

    return 0;
}

Do you like it? Share on social networks!

ДК
  • Nov. 26, 2019, 8:38 p.m.
  • (edited)

классная статья! Большое спасибо. Хотел бы добавить для тех, кто будет использовать это в другом классе- перед операторами и методами begin(), end() нужно поставить friend.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 24, 2025, 12:04 p.m.
    UPD: Переписал логику воспроизведения через стороннюю библиотеку BASS. Там выбрать можно
  • Evgenii Legotckoi
    April 16, 2025, 5:08 p.m.
    Благодарю за отзыв. И вам желаю всяческих успехов!
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…