无法汇总初始化类型结构的变量,其中包含在类模板中的位字段成员
unable to aggregate initialise a variable of type structure with bit field members wrapped in class template
struct EndianGuard_ {};
template<typename Type_>
struct EndianGuarded_ : EndianGuard_ {
EndianGuarded_() {
uint8_t* ByteData = (uint8_t*) this;
for (int i = 0; i < sizeof (Type_); i++) {
ByteData[i] = 0;
}
};
EndianGuarded_ (Type_ Value) : Value (Value) {};
~EndianGuarded_ () {};
Type_ Value;
};
struct Slot_2 {
uint8_t Slot : 4;
uint8_t Unit : 3;
uint8_t Bus : 2;
uint8_t Unused : 7;
};
EndianGuarded_<Slot_2> Slot = {7, 6, 1, 0};
我没有给定参数列表(int, int, int, int)
错误的构造函数匹配的实例。
是编译器错误吗?我的Bitfield结构有资格用于汇总初始化。
然后,当我尝试汇总一个 EndianGuard_
派生的结构时,包含数组成员时,我会得到类似的错误,尽管匹配构造函数已定义。
struct ProtocolResult_ : EndianGuard_ {
ProtocolResult_(const EndianGuarded_<char> Value[2]) {
this->Value[0] = Value[0];
this->Value[1] = Value[1];
};
static const ProtocolResult_
NORMAL_ANSWER,
BUSY;
EndianGuarded_<char> Value[2];
};
const ProtocolResult_ ProtocolResult_:: // no matching constructor with arguments
NORMAL_ANSWER = {{'0', '0' }}, // ({...})
BUSY = { '1', '1' }; // (char, char)
EndianGuarded_
不是汇总。聚集体没有构造函数,这种类型具有构造函数。因此,列表初始化语法将尝试根据您提供的参数来调用构造函数。
另外,即使您抛弃了构造函数, EndianGuarded_
仍然不会因17之前的C 规则而成为汇总。为什么?因为聚合不能拥有基类,而您的基础类也是如此。
和即使是C 17,EndianGuarded_
也没有4个子对象。它有2个;基类EndianGuard_
和成员子对象Value_
。因此,您需要初始化它会像{{/*whatever goes to the base class}, {7, 6, 1, 0}}
。
EndianGuard_
在您的示例中缺少定义,因此我将其添加为一个空结构。以下三个初始化将使用C 11进行编译:
struct EndianGuard_ { };
template<typename Type_>
struct EndianGuarded_ : EndianGuard_ {
EndianGuarded_ (Type_ Value) : Value (Value) {};
private:
Type_ Value;
};
struct Slot_2 {
int Slot : 4;
int Unit : 3;
int Bus : 2;
int Unused : 7;
};
EndianGuarded_<Slot_2> SlotX = {{7, 6, 1, 0}};
EndianGuarded_<Slot_2> SlotY({7, 6, 1, 0});
EndianGuarded_<Slot_2> SlotZ = Slot_2 {7, 6, 1, 0};
SlotY
的初始化可以说是最可读的,因为它隐含地表明您正在调用一个参数(outer ()
)的构造函数,并且该构造函数采用汇总的启动构造struct(Inner {}
)。
SlotZ
初始化使用隐式类型转换。标记构造函数explicit
,它将失败。Google C 样式需要一个单词的构造函数,以标记explicit
,因为它们可能会引起这样的惊喜。但是ymmv。
相关文章:
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如果基类包含双指针成员,则派生类的构造函数
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 成员包含其他继承类的继承类?
- 包含作为成员C++函数的结构数组
- 按类成员的顺序对包含类对象的C++向量进行排序
- 将 C# 对象(包含静态对象成员)作为参数传递给 C++/CLI 程序
- 如何使用包含内部类的类实例有效地从内部类访问成员?
- 当包含成员函数名为errno和cerrno时,g++7编译错误
- 拒绝包含某些公共静态数据成员的类型
- C++ 如何将关键字"friend"与两个类的成员函数一起使用 相互包含
- 为什么我应该在scanf()-家族成员中包含一个长度修饰符作为参数?有什么好处?使用长度修改器进行扫描的作用
- 是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
- 如果包含引用成员的类中缺少原始变量,为什么它仍然可以访问?
- C++:获取包含成员子对象的完整对象的地址
- 派生自包含成员的类,其模板参数是基类
- enable_if有条件地包含成员功能
- 如何创建包含成员函数和派生类的模板调用
- 我是否应该在将实现委托给子类的类中包含成员定义?
- 结构可以在方法主体中声明,但前提是它不包含成员字段初始值设定项。编译器错误与否?