如何初始化结构声明中的位域?

How to initialize a bitfield inside structure declaration?

当我尝试在结构声明中初始化一个位域时,MSVC++ 给我一个编译器错误:

struct SomeStruct
{
    bool a : 1 = false; // compiler error
    bool a = false : 1; // compiler error
} ;

在结构声明中初始化位字段的语法是什么?

我从 c​​lang 得到的错误非常明显:

bitfield member cannot have an in-class initializer

所以你根本做不到,你需要一个初始化成员的构造函数。

我有点惊讶,但显然 Visual Studio 在这里是正确的,如果我们看一下 C++11 标准草案 9.2 部分的语法,它说:

member-declarator:
  declarator virt-specifier-seqopt pure-specifieropt
  declarator brace-or-equal-initializeropt
  identifieropt attribute-specifier-seqopt: constant-expression

并且位域不允许有大括号或相等初始化器。我不清楚为什么存在此限制。这感觉就像我第一次意识到 in-class initializer makes a class a non-aggregate.

这显然是 defect:

The grammar for member-declarator (9.2 [class.mem]) does not, but should, allow for a brace-or-equal-initializer on a bit-field declarator.

Issues Found Implementing C++0x:

可以看出,这个问题显然也在 C++11 最终确定之前就被发现了
  1. (Richard Smith) class.mem: bitfield members cannot have in-class initializers

The grammar does not allow a brace-or-equal-initializer for a bitfield member. This seems like an oversight. A brace-or-equal-initializer after a constant- expression appears to be unambiguous.

clang behavior: clang implements the letter of the standard.

suggested resolution: Change the grammar as follows:

member-declarator:
    identifieropt attribute-specifier-seqopt : constant-expression brace-or-equal-initializeropt

但显然这种感觉是有漏洞的。