簡體   English   中英

位移運算符的結果類型是什么?

[英]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)很困惑。 為什么結果被簽名?

[expr.shift]

操作數應為整型或無作用域枚舉類型,並執行整型提升。 結果的類型是提升后的左操作數的類型。 [...]

因此,對於unsigned charint ,左操作數從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)1int窄,因此它們被提升為int ,相當於 C++ 實現中的int32_t 31是一個int ,所以它仍然是int 31u1uunsigned int ,所以它們仍然是unsigned int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM