你如何使用 clang 的新自定义大小 int 功能?

How do you use clang's new custom size int feature?

最近听说clang有一个新功能,_ExtInt。我知道它可以让你指定一个整数的大小(奇数或什至像 13 位整数),但你如何使用它?

_ExtInt 用作普通说明符。例如:

_ExtInt(13) foo;

这里你声明foo是13位的。记住不要在它前面放 shortlong 类型的关键字(因为它实际上没有意义),尽管你可以放 signedunsignedsigned 是默认值)。 请注意,您不能做类似的事情; _ExtInt(5) + _ExtInt(6)。根据 this 网站,那是因为:

The WG14 paper proposes integer promotion to the largest of the types (that is, adding an _ExtInt(5) and an _ExtInt(6) would result in an _ExtInt(6)), however the implementation does not permit that and _ExtInt(5) + _ExtInt(6) would result in a compiler error. This was done so that in the event that WG14 changes the design of the paper, we will be able to implement it without breaking existing programs.

这可以通过使用转换来解决:

(_ExtInt(6))AnExtInt5 + AnExtInt6 or static_cast<ExtInt(6)>(AnExtInt5) + AnExtInt6

不仅如此,如果您使用 C++,您还可以做一些非常疯狂的事情:

template<size_t WidthA, size_t WidthB>
  _ExtInt(WidthA + WidthB) lossless_mul(_ExtInt(WidthA) a, _ExtInt(WidthB) b) {
  return static_cast<_ExtInt(WidthA + WidthB)>(a) 
       * static_cast<_ExtInt(WidthA + WidthB)>(b);
} 

查看 here 了解更多详情。

补充说明:

  • 一个 int 添加到一个 _ExtInt(32) 将是一个整数。
  • 您的 int 大小可以增加 116,777,215 位。

注意:为了使用此功能,您需要最新版本的 clang,因为更改是在 2020 年 4 月 21 日进行的。