固定宽度整数类型的整数文字
对于像这样的固定宽度整数类型的整数文字是否有一些 c++ 建议?
// i's type is unsigned int
auto i = 10u;
// j's type is uint32_t
auto j = 10u32;
回答
是:P1280R0 整数宽度文字(2018 年 10 月 5 日发布)。
它提出了以下文字:
namespace std::inline literals::inline integer_literals {
constexpr uint64_t operator ""u64 (unsigned long long arg);
constexpr uint32_t operator ""u32 (unsigned long long arg);
constexpr uint16_t operator ""u16 (unsigned long long arg);
constexpr uint8_t operator ""u8 (unsigned long long arg);
constexpr int64_t operator ""i64 (unsigned long long arg);
constexpr int32_t operator ""i32 (unsigned long long arg);
constexpr int16_t operator ""i16 (unsigned long long arg);
constexpr int8_t operator ""i8 (unsigned long long arg);
}
以及它的更新P1280R1,“将返回类型修改为实际上是[u]int_leastXX_t
和朋友。这是为了确保我们实际上正在替换[U]INTxx_C
宏,因为它们返回一个[u]int_leastXX_t
”:
namespace std::inline literals::inline integer_literals {
constexpr uint_least64_t operator ""u64 (unsigned long long arg);
constexpr uint_least32_t operator ""u32 (unsigned long long arg);
constexpr uint_least16_t operator ""u16 (unsigned long long arg);
constexpr uint_least8_t operator ""u8 (unsigned long long arg);
constexpr int_least64_t operator ""i64 (unsigned long long arg);
constexpr int_least32_t operator ""i32 (unsigned long long arg);
constexpr int_least16_t operator ""i16 (unsigned long long arg);
constexpr int_least8_t operator ""i8 (unsigned long long arg);
}
有一个 2019-06-12 更新P1280R2使文字consteval
而不是constexpr
.
- And does multiplying two large `uint16_t`s and storing the result in a `uint16_t` variable result in wraparound or undefined behavior? Integer math in C/C++ is a horrible mess.
-
@PeteBecker 1) "platform doesn't support uint32, so I won't compile 5u32" is straightforward compiler error
2) "in some random place where uint_least32_t is used, some overloading is now ambiguous" (suppose that uint32_least_t=unsigned long long and the same example will be broken as in P1280) is less straight forward.I of course agree that you might want uint32_least_t, but why not use 5u_least32 ?
- @RiaD -- it's `uint32_t` that will fail on some other platform. `uint_least32_t` is **always** available; `uint32_t` won't exist on (admittedly unusual) platforms that don't have a native 32-bit integer type. That's an inherent ambiguity with fixed-size integer types: you might want an exact size, or you might want something large enough to hold some number of bits.