Search code examples
c++bitset

Bit width of a class


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


Solution

  • 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.