Question

I need the following two very similar structures in my code:

union ArrayEntry2Byte {          union ArrayEntry4Byte {
  struct {                         struct {
    char foo : 1;                    char foo : 1;
    short bar : 15;                   int bar : 31;
  };                               };
  short foobar;                    int foobar;
  // other code                    // other code
};                               };

In order to increase maintainability and elegance of this code, I want to remove one of these structures using template programming:

template<typename value_type>
union ArrayEntry {
  struct {
    char foo : 1;
    value_type bar : 15;
  };
  value_type foobar;
  // other code
};

However, the bit field brings me into trouble. All I need is something like this:

value_type bar : (value_type == short ? 15 : 31);

But, well, that’s obviously no correct syntax. How can I elegantly solve this problem?

Was it helpful?

Solution

Here is a C++11 solution:

#include <limits>

template <typename value_type>
union ArrayEntry {
    struct {
        char foo : 1;
        value_type bar : std::numeric_limits<value_type>::digits;
    };
    value_type foobar;
    // other code
};

OTHER TIPS

Create a private template that returns the correct value:

template<typename T>
struct bitFieldValue : std::integral_constant<int, 31>
{ };

template<>
struct bitFieldValue<short> : std::integral_constant<int, 15>
{ };

Then later on:

value_type bar : bitFieldValue<value_type>::value;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top