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.

  1. enum ColorTypes {
  2. Green,
  3. Yellow,
  4. Red
  5. };

So enumerations with scope

  1. enum class ColorTypes {
  2. Green,
  3. Yellow,
  4. Red
  5. };

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 () .

  1. enum class ColorTypes { Green, Yellow, Red };
  2.  
  3. ColorTypes currentType_1 = ColorTypes::Green; // Ok
  4. ColorTypes currentType_2 = 2; // Error, conversion is impossible
  5. int currentType_3 = ColorTypes::Red; // Error, conversion is impossible
  6. int currentType_4 = Red; // Error, Red does not exist in this scope
  7. 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 ...

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

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

  1. enum class ColorTypes {
  2. Green = 15, // 15
  3. Yellow, // 16
  4. Red = 24, // 24
  5. Black = ColorTypes::Red, // 24
  6. Blue // 25
  7. };

Using switch case for enumerations

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

  1. ColorTypes currentType = ColorTypes::Green;
  2.  
  3. switch (currentType)
  4. {
  5. case ColorTypes::Green: std::cout << "Green"; break;
  6. case ColorTypes::Yellow: std::cout << "Yellow"; break;
  7. case ColorTypes::Black: std::cout << "Black"; break;
  8. case ColorTypes::Blue: std::cout << "Blue"; break;
  9. default: std::cout << "Unknown Type"; break;
  10. }

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:

  1. enum SideTypes {
  2. Top,
  3. Bottom,
  4. Right,
  5. Left
  6. };
  7.  
  8. enum ColorTypes {
  9. Green = 8,
  10. Yellow,
  11. Red,
  12. Blue
  13. };
  14.  
  15. int main(int argc, char *argv[])
  16. {
  17. ColorTypes currentType = ColorTypes::Green;
  18.  
  19. switch (currentType)
  20. {
  21. case SideTypes::Top: std::cout << "Top Side"; break;
  22. case ColorTypes::Green: std::cout << "Green"; break;
  23. case ColorTypes::Yellow: std::cout << "Yellow"; break;
  24. case ColorTypes::Red: std::cout << "Red"; break;
  25. case ColorTypes::Blue: std::cout << "Blue"; break;
  26. default: std::cout << "Unknown Type"; break;
  27. }
  28.  
  29. return 0;
  30. }

At best, the compiler will throw Warning.

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

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:

  1. enum class SideTypes {
  2. Top,
  3. Bottom,
  4. Right,
  5. Left
  6. };
  7.  
  8. enum class ColorTypes {
  9. Green = 8,
  10. Yellow,
  11. Red,
  12. Blue
  13. };
  14.  
  15. int main(int argc, char *argv[])
  16. {
  17. ColorTypes currentType = ColorTypes::Green;
  18.  
  19. switch (currentType)
  20. {
  21. case SideTypes::Top: std::cout << "Top Side"; break;
  22. case ColorTypes::Green: std::cout << "Green"; break;
  23. case ColorTypes::Yellow: std::cout << "Yellow"; break;
  24. case ColorTypes::Red: std::cout << "Red"; break;
  25. case ColorTypes::Blue: std::cout << "Blue"; break;
  26. default: std::cout << "Unknown Type"; break;
  27. }
  28. return 0;
  29. }

The compiler will generate a compilation error:

  1. error: could not convert Top from SideTypes to ColorTypes
  2. case SideTypes::Top: std::cout << "Top Side"; break;
  3. ^

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.

  1. enum class SideTypes : short int {
  2. Top,
  3. Bottom,
  4. Right,
  5. Left
  6. };

Iterator for enumerations

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

  1. #include <iostream>
  2.  
  3. enum class ColorTypes
  4. {
  5. Blue,
  6. Red,
  7. Green,
  8. Purple,
  9. First=ColorTypes::Blue, // participant of the enumerator for the first element
  10. Last=ColorTypes::Purple // participant of the enumerator for the last item
  11. };
  12.  
  13. ColorTypes operator++(ColorTypes& x)
  14. {
  15. // std::underlying_type converts the type of ColorTypes into an integer type, under which the given enum was declared
  16. return x = static_cast<ColorTypes>(std::underlying_type<ColorTypes>::type(x) + 1);
  17. }
  18.  
  19. ColorTypes operator*(ColorTypes c)
  20. {
  21. return c;
  22. }
  23.  
  24. ColorTypes begin(ColorTypes r)
  25. {
  26. return ColorTypes::First;
  27. }
  28.  
  29. ColorTypes end(ColorTypes r)
  30. {
  31. ColorTypes l=ColorTypes::Last;
  32. return ++l;
  33. }
  34.  
  35. int main(int argc, char *argv[])
  36. {
  37. // We use parentheses to instantiate the enumeration
  38. for(const auto& c : ColorTypes())
  39. {
  40. std::cout << static_cast<int>(c) << std::endl;
  41. }
  42.  
  43. return 0;
  44. }

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
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html