从 long long int 转换为 uint64_t 的推荐方法是什么?

What is the recommended way to convert from long long int to uint64_t?

考虑一个 return 具有 long long int 值的函数。尽管它 return 是 long long int,但逻辑保证它始终为正。我想使用分配给 uint64_t 的 return 值。鉴于逻辑是正确的,建议使用什么方法进行此转换?我应该只分配给它还是进行静态转换?

这是一个隐式转换,integral convertion,不需要转换:

If the destination type is unsigned, the resulting value is the smallest unsigned value equal to the source value modulo 2n where n is the number of bits used to represent the destination type. That is, depending on whether the destination type is wider or narrower, signed integers are sign-extended or truncated and unsigned integers are zero-extended or truncated respectively.

static_cast 没有任何价值。

A static_assert 可用于防止截断,例如:

static_assert(sizeof(uint64_t) >= sizeof(long long), "Truncation detected.");`

还有boost::numeric_cast:

The fact that the behavior for overflow is undefined for all conversions (except the aforementioned unsigned to unsigned) makes any code that may produce positive or negative overflows exposed to portability issues.

numeric_cast returns the result of converting a value of type Source to a value of type Target. If out-of-range is detected, an overflow policy is executed whose default behavior is to throw an an exception (see bad_numeric_cast, negative_overflow and positive_overflow ).