[英]What is the value category of result yielded from shift operators, bit-wise operators, and sizeof operator?
[英]What is the result type of the bit shift operator?
考慮以下清單:
#include <type_traits>
#include <cstdint>
static_assert(std::is_same_v<decltype(31), int32_t>);
static_assert(std::is_same_v<decltype(31u), uint32_t>);
static_assert(std::is_same_v<decltype((signed char)1 << 1), int32_t>);
static_assert(std::is_same_v<decltype((signed char)1 << 1u), int32_t>);
static_assert(std::is_same_v<decltype((unsigned char)1 << 1), int32_t>);
// Signed result for unsigned char
static_assert(std::is_same_v<decltype((unsigned char)1 << 1u), int32_t>);
// But unsigned for uint32_t
static_assert(std::is_same_v<decltype(1u << 1u), uint32_t>);
它與 GCC 和 Clang 編譯得很好。我對operator<<(uint8_t, uint32_t)
很困惑。 為什么結果被簽名?
操作數應為整型或無作用域枚舉類型,並執行整型提升。 結果的類型是提升后的左操作數的類型。 [...]
因此,對於unsigned char
和int
,左操作數從unsigned char
提升為int
1 (請參閱[conv.prom] ),結果類型是左操作數之一,因此int
。
1至少在大多數常見平台上(其中sizeof(char) < sizeof(int)
),否則如果sizeof(char) == sizeof(int)
,它可能會提升為unsigned int
。
對於<<
運算符,左操作數使用整數提升提升。 整數提升中有一些技術細節,但主要是: 窄於int
的類型被提升為int
。 其他integer類型不變。
<<
運算符的結果類型是提升后其左操作數的類型。
在您的示例中, (signed char)1
和(unsigned char)1
比int
窄,因此它們被提升為int
,相當於 C++ 實現中的int32_t
。 31
是一個int
,所以它仍然是int
。 31u
和1u
是unsigned int
,所以它們仍然是unsigned int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.