Best/proper way to define uint64_t constants

放肆的年华 提交于 2019-12-23 18:45:05

问题


constexpr auto v = static_cast<std::uint64_t>(1) << 32; is not ideal, because of the tedious syntax and the cast which is semantically indirect. From this thread, I learned constexpr auto v = UINT64_C(1) << 32; However, the precise semantics of the macro is

expands to an integer constant expression having the value specified by its argument and the type uint_least64_t.

Therefore, it's not exactly uint64_t. I'm wondering what is the best/proper way to define uint64_t constants.

Note that unsigned long long doesn’t necessarily map to uint64_t.

Update

I'm reluctant to use functional/C-style cast, because some (e.g., Google C++ Coding Style) say it's from C, and modern C++ should avoid using them. Looks like I should have my own opinion on this, instead of blindly following others.


回答1:


Therefore, it's not exactly uint64_t. I'm wondering what is the best/proper way to define uint64_t constants.

If you want to be absolutely sure, you can write uint64_t(1) (possibly std::-qualified) instead as a shorter alternative to your static_cast.

For practical purposes, UINT64_C is fine though. Implementations aren't required to define uint64_t if they don't provide any type which meets its requirements. It makes sense because of that to define UINT64_C in terms of uint_least64_t.

But on implementations where uint64_t does exist -- and you're implicitly already assuming you're using such an implementation -- uint64_t and uint_least64_t must have the exact same range, are it would pretty much require malice on the implementor's part to not make them the exact same type.

P.S. Since this is tagged language-lawyer: there is no guarantee that uint64_t(1) << 32 still has type uint64_t. Hypothetically, an implementation may provide a larger-than-64-bit int type, in which case uint64_t would be promoted to int.




回答2:


There are specifiers for exactly this, using L makes your integer literal a long, LL a long long and ULL an unsigned long long, or, uint64_t (most of the time).

Or just drop auto all together and just let the compiler make the implicit cast.



来源:https://stackoverflow.com/questions/48909995/best-proper-way-to-define-uint64-t-constants

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