std :: Byte位运算符|,&, ^,〜:为什么要施放无签名的int?

发布于 2025-02-11 07:18:26 字数 890 浏览 2 评论 0原文

根据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;^应该类似地实现)

为什么lr需要将其施放到int int int nunsigned时代码> std :: byte 的基础类型是char unsigned

注意:我知道char unsigned {} | char unsigned {}int中结果导致,因为在应用 bitwise或之前将每个操作数升级为intunsigned {} | 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜扑 2025-02-18 07:18:26

对于比int较小的整数类型,在应用操作员之前,它们会晋升为int。这意味着,如果您

return std::byte{ l | r };

有一个签名的整数。通过使用

return std::byte{ static_cast<unsigned>(l) | static_cast<unsigned>(r) }

您明确将操作数转换为未签名的整数,以免促销int发生。

在C ++ 20之前,这可能会有所作为,因为与未签名的整数类型不同,不需要使用两者的补体表示形式。

For integer types that are smaller then an int, they are promoted to an int before the operator is applied. That means if you had

return std::byte{ l | r };

then you would have a signed integer. By using

return std::byte{ static_cast<unsigned>(l) | static_cast<unsigned>(r) }

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文