定义uint64_t常数的最佳/正确方法 [英] Best/proper way to define uint64_t constants
问题描述
constexpr auto v = static_cast<std::uint64_t>(1) << 32;
并不理想,因为语法繁琐且强制转换在语义上是间接的.从此线程中,我了解到constexpr auto v = UINT64_C(1) << 32;
,但是,
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
扩展为具有指定值的整数常量表达式 根据其参数和类型
uint_least64_t
.
expands to an integer constant expression having the value specified by its argument and the type
uint_least64_t
.
因此,它不完全是uint64_t
.我想知道定义uint64_t
常数的最佳/正确方法是什么.
Therefore, it's not exactly uint64_t
. I'm wondering what is the best/proper way to define uint64_t
constants.
请注意,unsigned long long
不一定映射到uint64_t
.
Note that unsigned long long
doesn’t necessarily map to uint64_t
.
更新
我不愿意使用函数式/C风格的强制转换,因为有些人(例如Google C ++编码风格)说它是C语言,现代C ++应该避免使用它们.看来我应该对此有自己的见解,而不是一味地跟从别人.
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.
推荐答案
因此,它不完全是
uint64_t
.我想知道定义uint64_t
常数的最佳/正确方法是什么.
Therefore, it's not exactly
uint64_t
. I'm wondering what is the best/proper way to defineuint64_t
constants.
如果您想绝对确定,可以写uint64_t(1)
(可能是std::
合格的)来代替static_cast
.
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
.
出于实际目的,UINT64_C
很好.如果实现不提供满足其要求的任何类型,则不需要定义uint64_t
.这样做很有意义,因为可以根据uint_least64_t
定义UINT64_C
.
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
.
但是在确实存在uint64_t
的实现上-并且您已经隐含地假设您正在使用这样的实现-uint64_t
和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.由于这是标记为Language-lawyer的标记,因此无法保证uint64_t(1) << 32
仍具有类型uint64_t
.假设,一个实现可以提供大于64位的int
类型,在这种情况下,uint64_t
将被提升为int
.
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
.
这篇关于定义uint64_t常数的最佳/正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!