Under what circumstances should I use a fixed-width integer for the enum class in C ++ 11

In what circumstances should I use this:

enum class MyFixedType : uint32_t // or any other fixed width integer type
{
    ID1,
    ID2,
    ID3
};

above this:

enum class MyType
{
    ID1,
    ID2,
    ID3
};

?

+4
source share
2 answers

A few scenarios from the top of my head where this might be useful:

  • There is limited space, and you really don't need standard int-size enums. If you are on a system where integers are stored in 64-bit format and you have less than 255 different enumeration values, you may need to specify what you want / need smaller bits for each enum element.

  • . , , , , , , .

  • , , +, 2 , 2 ( , enum , ).

, . , , , , .

+4

, - .

, 32- , 3 :

  • 8- id
  • 8- .
  • 32-

:

#include <iostream>

struct SomeDeviceMemoryMap1
{
    unsigned int  id : 8;
    unsigned int  status : 8;
    unsigned int  reserved : 16;
    unsigned int  color : 32;
};


int main()
{
    std::cout << sizeof(SomeDeviceMemoryMap1)<<std::endl;

    SomeDeviceMemoryMap1 m1;
    m1.id = 1;
    m1.status = 5;
    m1.color = 33;
}

++ 03, , .

++ 11 . :

#include <iostream>

enum class MyFixedType1 : uint8_t
{
    ID1=0,
    ID2,
    ID3
};

enum class MyFixedType2 : uint8_t
{
    STATUS1,
    STATUS2,
    STATUS3=5
};

enum class MyFixedType3 : uint32_t
{
    RED,
    BLUE = 33,
    BLACK
};

struct SomeDeviceMemoryMap2
{
    MyFixedType1  id;
    MyFixedType2  status;
    unsigned int  reserved : 16;
    MyFixedType3  color;
};


int main()
{
    std::cout << sizeof(SomeDeviceMemoryMap2)<<std::endl;

    SomeDeviceMemoryMap2 m2;
    m2.id = MyFixedType1::ID1;
    m2.status = MyFixedType2::STATUS3;
    m2.color = MyFixedType3::BLUE;
}
+1

Source: https://habr.com/ru/post/1544183/


All Articles