gpt4 book ai didi

c++ - 为什么 digits10 引用整数类型 0?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:58 26 4
gpt4 key购买 nike

以下代码:

#include <iostream>
#include <limits>
#include <cstdint>

int main()
{
std::cout << std::numeric_limits<std::uint64_t>::digits10 << "\n"
<< std::numeric_limits<std::uint64_t&>::digits10 << "\n";
}

输出

19
0

我希望 std::uint64_t&std::uint64_t 具有相同的值:是否存在这种差异的原因?

最佳答案

18.3.2.1/2:

Specializations shall be provided for each arithmetic type, both floating point and integer, including bool. The member is_specialized shall be true for all such specializations of numeric_limits.

因此我们知道这些非引用类型将存在专门化。然后 18.3.2.3/1:

The default numeric_limits template shall have all members, but with 0 or false values.

我怀疑这是这样做的,因为你总是可以在 is_specialized 上使用 static_assert 来强制编译错误,但可能有一些模板应用程序,其中 0 是一个或多个的默认值的限制。如果您希望能够测试引用,只需通过 std::remove_reference 运行它即可。

我不确定为您自己的类型特化 numeric_limits 是否合法。 18.3.2.1/4 中的标准说:

Non-arithmetic standard types, such as complex (26.4.2), shall not have specializations.

我个人将这句话理解为“该标准不会为非算术标准库类型提供特化,但为用户类型特化是完全合法的”。您可以像完全禁止任何未提供的专业一样轻松地阅读此内容。

关于c++ - 为什么 digits10 引用整数类型 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29392607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com