[英]Type of bit-field members
Theoretically, we have two options to chose the type of a bit field member: 从理论上讲,我们有两种选择来选择位字段成员的类型:
So what is the actually the type of bit-field members (I couldn't find so far hints in the standard – C and C++ alike) and is there any difference in between C and C++? 那么实际上是什么类型的位域成员(我在标准中找不到迄今为止的提示--C和C ++一样)并且C和C ++之间有什么区别?
Although being aware that a specific compiler is not the reference, I tried to get at least some hints via C++ function overloads and typeid operator : 虽然知道特定的编译器不是引用,但我试图通过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;
}
Output (GCC 5.4.0 under linux) was totally surprising and – in my eyes at least – contradicting: 输出(Linux下的GCC 5.4.0)完全令人惊讶 - 至少在我看来 - 是矛盾的:
ui
ui
h
t
h
t
j
So if type, according to typeid operator, is unsigned char and unsigned short respectively, why is unsigned int selected during overload resolution? 因此,如果type,根据typeid运算符,分别是unsigned char和unsigned short,为什么在重载解析期间选择unsigned int? Possibly even a GCC bug?
可能甚至是GCC的错误?
Addendum: GCC 8.1 (linux) still exhibits the same behaviour. 附录:GCC 8.1(linux)仍然表现出相同的行为。
From C++ standard § 10.3.10.1 (class.bit) : 从C ++标准§10.3.10.1(class.bit) :
The bit-field attribute is not part of the type of the class member.
bit-field属性不是类成员类型的一部分。
(I must have overlooked this phrase from the standard when posting the question...) (在发布问题时,我一定忽略了标准中的这句话......)
So the standard is clear about the type of a bit-field member, it is equal to the underlying type. 因此标准清楚地表明了位字段成员的类型,它等于底层类型。
Thanks to Davis Herring for giving me the appropriate hints. 感谢Davis Herring为我提供了适当的提示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.