struct bitfield {
int i = 0; // ok
int j : 8 = 0; // error: lvalue required as left operand of assignment
};
What is the correct syntax to initialize bit-fields using C++11 "in-class initialization" feature?
struct bitfield {
int i = 0; // ok
int j : 8 = 0; // error: lvalue required as left operand of assignment
};
What is the correct syntax to initialize bit-fields using C++11 "in-class initialization" feature?
This was raised as Core Issue 1341 to the C++ standard, but was rejected by the C++ Core Working Group in October 2015 as NAD ("not a defect") - see http://open-std.org/JTC1/SC22/WG21/docs/cwg_closed.html#1341
You cannot initialize bit-fields in-class. Paragraph 9.2 of the C++11 Standard specifies the grammar for class member declarators:
As you can see, declarators for bit-field members cannot be terminated by a brace-or-equal-initializer.
You can write a constructor with initializer list to give default values to your bitfields.
You can also create read-only fields with default values.
You cannot (in C++11) in-class initialize bitfields.
In MSVC and gcc (with extensions), the anonymous
union
andstruct
code lets you get around this a bit.where we mix a fixed size
raw
with aunion
over bitfields, then in-class initialize theraw
element.