C++ 模板编程和位字段

C++ 模板编程和位字段,c++,templates,bit-fields,C++,Templates,Bit Fields,我的代码中需要以下两个非常相似的结构: union ArrayEntry2Byte { union ArrayEntry4Byte { struct { struct { char foo : 1; char foo : 1; short bar : 15; int bar : 31; };

我的代码中需要以下两个非常相似的结构:

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
};                               };
为了提高代码的可维护性和优雅性,我想使用模板编程删除以下结构之一:

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

但是,这显然是不正确的语法。如何优雅地解决此问题?

创建一个返回正确值的私有模板:

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

template<>
struct bitFieldValue<short> : std::integral_constant<int, 15>
{ };
模板
结构bitFieldValue:std::整型常量
{ };
模板
结构bitFieldValue:std::整型常量
{ };
随后:

value_type bar : bitFieldValue<value_type>::value;
value\u类型栏:bitFieldValue::value;

下面是一个C++11解决方案:

#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
};
#包括
模板
联合ArrayEntry{
结构{
查富:1;
值\类型栏:标准::数字\限制::数字;
};
值_型foobar;
//其他代码
};

既然可以使用
std::numeric\u limits::digits
,为什么还要创建特征?@rici没有意识到这一点。好的+这可能是一个初学者的问题,但是什么是私有模板?@user1494080私有模板我的意思是在你工会的
private:
标签下创建它们。类似于类的私有数据成员。这很好,但是,我认为我过于简化了我的问题。假设我们在联合体中有以下结构:
struct{char foo:1;short bar1:7;short bar2:8}
或分别
struct{char foo:1;int bar1:15;int bar2:16}
。然后我必须求助于0x499602D2的解决方案,不是吗?@user1494080是的,在这种情况下,如果不能使用某种公式从
value\u type
type的位数中提取这些幻数,那么你必须更喜欢0x499602D2的解决方案。实际上它们可以。:)我不知所措,你的解决方案非常有效。
#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
};