gpt4 book ai didi

c++ - 为什么 std::numeric_limits::max() 返回 0?

转载 作者:IT老高 更新时间:2023-10-28 22:04:07 31 4
gpt4 key购买 nike

我在 std::numeric_limits<seconds>::max() 中发现了一个有趣的问题。返回 0。答案是使用 seconds::max()std::numeric_limits<seconds::rep>::max()相反,但我很想知道为什么会发生这种情况。我希望它在编译时失败或正常工作。以下代码演示了 gcc 4.9.3 的问题。

#include <iostream>
#include <limits>
#include <chrono>

using namespace std;
using namespace std::chrono;

int main(int /*argc*/, const char* /*argv*/[])
{
const auto maxSeconds = std::numeric_limits<seconds>::max();
std::cerr << maxSeconds.count() << "\n";
const auto maxSeconds2 = seconds::max();
std::cerr << maxSeconds2.count() << "\n";
return 0;
}

我在 chrono 头文件中看不到任何隐式转换。如果一个 duration已隐式转换为数字类型并且符号丢失或 bool您最终可能会得到最小值为零 - 但最大值为零是没有意义的。


正如 TartanLlama 指出的,默认特化使用默认构造函数,因此返回 0。

深入研究 standard 的旧拷贝我看到以下命令:

18.3.2.3 Class template numeric_limits [numeric.limits]

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

稍后:

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

The value of each member of a specialization of numeric_limits on a cv-qualified type cv T shall be equal to the value of the corresponding member of the specialization on the unqualified type T.

缺少的是解释为什么委员会认为这比编译失败更好。是否需要提供库缺陷报告?


更新:我已将此问题作为问题提交给 ISO 委员会

https://issues.isocpp.org/show_bug.cgi?id=186

最佳答案

std::numeric_limits不专门用于 std::chrono::seconds . std::numeric_limits 中给出了所有数据成员和函数的默认定义。以避免非专业类型的编译器错误。 numeric_limits<T>::max() 的默认版本只需返回 T() ,即 0在这种情况下。

您可以检查 std::numeric_limits专门用于给定的 T在编译时通过检查 std::numeric_limits<T>::is_specialized , 默认为 false .

关于c++ - 为什么 std::numeric_limits<seconds>::max() 返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35575276/

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