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

喜夏-厌秋 提交于 2020-07-22 14:12:09

问题


Recently, I heard that clang got a new feature, _ExtInt. I know that it lets you specify the size of an integer (odd or even like 13-bit int), but how do you use it?


回答1:


_ExtInt is to be used as a normal specifier. For example:

_ExtInt(13) foo;

Here you declared foo to be of 13 bits. Remember to not put short or long type of keywords before it (cause it wouldn't really make sense), though you can put signed or unsigned (signed is default). Note that you aren't allowed to do things like; _ExtInt(5) + _ExtInt(6). According to this website, that is because:

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.

This can be worked around by using casts:

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

Not only that, but if you use c++ you can do some really crazy stuff:

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);
} 

Look here for some more details.

Extra notes:

  • An int added to an _ExtInt(32) will be an int.
  • Your int size can go up 1 to 16,777,215 bits.

Note: In order to use this feature, you will need the latest version of clang, as the change was made on 4/21/2020.



来源:https://stackoverflow.com/questions/61411865/how-do-you-use-clangs-new-custom-size-int-feature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!