std :: Byte位运算符|,&, ^,〜:为什么要施放无签名的int?
根据std :: byte
在 cppReference上的文档a>,用于操作员的实现|
std :: byte
应该等效于
constexpr std::byte operator|(std::byte l, std::byte r) noexcept
{
return std::byte{ static_cast<unsigned>(l) | static_cast<unsigned>(r) };
}
(操作员&amp;
,^
,〜
应该类似地实现)
为什么l
和r
需要将其施放到int int int nunsigned
时代码> std :: byte 的基础类型是char unsigned
?
注意:我知道char unsigned {} | char unsigned {}
在int
中结果导致,因为在应用 bitwise或之前将每个操作数升级为int
; unsigned {} | unsigned {}
返回unsigned
,并且没有促销。但是,在这种情况下,我不知道哪些问题可能会导致这样的促销。
According to std::byte
's documentation on cppreference, the implementation of operator|
for std::byte
should be equivalent to
constexpr std::byte operator|(std::byte l, std::byte r) noexcept
{
return std::byte{ static_cast<unsigned>(l) | static_cast<unsigned>(r) };
}
(Operators &
, ^
, ~
should be implemented similarly)
Why do l
and r
need to get cast to int unsigned
if std::byte
's underlying type is char unsigned
?
Note: I'm aware that char unsigned{} | char unsigned{}
results in an int
because each operand gets promoted to int
before the bitwise or is applied; while unsigned{} | unsigned{}
returns an unsigned
and no promotion happens. However, I don't understand which issues may such a promotion cause in this context.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于比
int
较小的整数类型,在应用操作员之前,它们会晋升为int
。这意味着,如果您有一个签名的整数。通过使用
您明确将操作数转换为未签名的整数,以免促销
int
发生。在C ++ 20之前,这可能会有所作为,因为与未签名的整数类型不同,不需要使用两者的补体表示形式。
For integer types that are smaller then an
int
, they are promoted to anint
before the operator is applied. That means if you hadthen you would have a signed integer. By using
You explicitly convert the operands to unsigned integers so that no promotion to
int
happens.This could make a difference before C++20 as signed integers were not required to use a two's complement representation unlike unsigned integer types.