Bit width of a class

Viewed 92

there is a class declared as:

class Payload {
    uint8_t m_a : 1;
    uint8_t m_b : 5;
    uint8_t m_c : 2;
    uint8_t m_d : 4;
};

you see, the sizeof(Payload) == 2. So far so good. The total amount of bits is 12, it exceeds the 8bit thus 2Bytes are occupied.

But is there a way how to get the amount of bits the class declares? I mean to return '12'...? Sure to make the algorithm working for any kind of class definining bitfields as above, theoreticaly of any size...

2 Answers

sizeof(Payload)*CHAR_BIT. This gets the size of the structure in bytes and multiplies it by the number of bits per byte (it’s technically not always 8). This works because bitfield-containing structs cannot have a size in bits which is not a multiple of CHAR_BIT. The compiler will add padding bits after the last member.

No, not in a standard-conformant way.

[class.bit]/1:

the bit-field attribute is not part of the type of the class member

which means this information cannot be extracted at compile time. Any kind of attempt to find this information using runtime introspection techniques would rely on, at best, implementation defined behaviour.

Related