1

I'm using a macro to compute the size of a bit-field. Would it be possible to use a template?

Code example:

#include <stdio.h>

/*! 
@param reg a bit-fields structure
@param field name of one of the fields in 'reg'
*/
#define GET_FIELD_MAX(reg, field) ({ \
    decltype(reg) r; \
    r.field = ~0UL; \
    r.field; })

struct A {
    unsigned a : 3;
    unsigned b : 4;
};

int main()
{
  A x;
  printf("b size = %d", GET_FIELD_MAX(x, b));
}

Output:

b size = 15
yakoda
  • 147
  • 6
  • Please make a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). What is reg, field ? Why do you need to use a template ? Why don't you use https://en.cppreference.com/w/cpp/language/bit_field ? – coincoin Sep 12 '19 at 14:54
  • 1
    No, because there is no way to pass `field` into a template, as `&RegType::field` is illegal if `field` is a bitfield. – Eric Sep 12 '19 at 23:44
  • Somewhat related question → https://stackoverflow.com/questions/55064622/get-size-of-bit-field-struct-members -- nevertheless the C-style designated initializer is not really usable (in the standard) so your code can be adapted to use a immediately-invoked lambda. – user202729 Nov 02 '22 at 01:06

0 Answers0