位字段成员的类型
Type of bit-field members
理论上,我们有两个选项来选择位字段成员的类型:
- 基础类型的类型。
- 位数适合的最小类型。
那么位域成员的实际类型是什么(到目前为止,我在标准中找不到提示 - C 和 C++ 都一样(,C 和 C++ 之间有什么区别吗?
尽管意识到特定的编译器不是参考,但我试图通过C++函数重载和typeid运算符至少获得一些提示:
#include <typeinfo>
struct S
{
unsigned int n4 : 4;
unsigned int n12 : 12;
};
void f(unsigned char)
{
std::cout << "uc" << std::endl;
}
void f(unsigned short)
{
std::cout << "us" << std::endl;
}
void f(unsigned int)
{
std::cout << "ui" << std::endl;
}
int main(int argc, char* argv[])
{
S s; s.n4 = 0; s.n12 = 0;
f(s.n4);
f(s.n12);
std::cout << typeid(s.n4).name() << std::endl;
std::cout << typeid(s.n12).name() << std::endl;
std::cout << typeid(unsigned char).name() << std::endl;
std::cout << typeid(unsigned short).name() << std::endl;
std::cout << typeid(unsigned int).name() << std::endl;
return 0;
}
输出(linux 下的 GCC 5.4.0(完全令人惊讶,至少在我看来是矛盾的:
ui
ui
h
t
h
t
j
那么,如果根据typeid运算符,type分别是无符号字符和无符号短字符,为什么在重载解析期间选择无符号int?甚至可能是海湾合作委员会的错误?
附录:GCC 8.1(linux(仍然表现出相同的行为。
从C++标准§ 10.3.10.1 (class.bit(:
位字段属性不是类成员类型的一部分。
(在发布问题时,我一定忽略了标准中的这句话......
因此,标准明确了位字段成员的类型,它等于底层类型。
感谢戴维斯·赫林给了我适当的提示。
相关文章:
- 访问C++中的类型成员
- 具有 STL 向量类型成员的类的复制内存
- 重载具有 2 个相同数据类型成员的构造函数
- std::void_t 和嵌套的非类型成员
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 使用各种数据类型成员创建对象的简便方法
- 将类类型成员定义为公共和私有之间有什么区别?
- 结构类型成员的默认构造函数中的默认参数
- 如何传递模板模板非类型成员函数指针
- 文本类类型成员函数约束
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- C++:将模板参数的模板类型成员加为好友的语法正确吗
- C++静态结构类型成员初始化
- C++:作为引用或指针的基类型成员变量
- 左值引用类型成员的用户定义移动构造函数
- 具有指针类型成员的类在 MSVS2012@debug 下销毁时失败.程序错误或错误源
- CRTP -- 访问不完整的类型成员
- 为什么C++默认初始化不对非类类型成员进行零初始化
- 请求非类类型成员