固定宽度整数类型的整数文字

康桓瑋*_*康桓瑋 19 c++ c++11

对于像这样的固定宽度整数类型的整数文字是否有一些 c++ 建议?

// i's type is unsigned int
auto i = 10u;
// j's type is uint32_t
auto j = 10u32;
Run Code Online (Sandbox Code Playgroud)

bol*_*lov 24

是: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);
}
Run Code Online (Sandbox Code Playgroud)

以及它的更新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);
}
Run Code Online (Sandbox Code Playgroud)

有一个 2019-06-12 更新P1280R2使文字consteval而不是constexpr.

  • 将两个大的“uint16_t”相乘并将结果存储在“uint16_t”变量中是否会导致环绕或未定义的行为?C/C++ 中的整数数学是一团糟。 (6认同)
  • @PeteBecker 1)“平台不支持 uint32,所以我不会编译 5u32”是简单的编译器错误 2)“在使用 uint_least32_t 的某个随机位置,某些重载现在不明确”(假设 uint32_least_t=unsigned long long并且与 P1280 中的相同示例将被破坏)不太直接。我当然同意您可能想要 uint32_least_t ,但为什么不使用 5u_least32 呢? (4认同)
  • @RiaD——“uint32_t”在其他平台上会失败。`uint_least32_t` **始终**可用;`uint32_t` 将不会存在于没有本机 32 位整数类型的(诚然不寻常的)平台上。这是固定大小整数类型固有的歧义:您可能想要一个精确的大小,或者您可能想要足够大的东西来容纳一定数量的位。 (3认同)