Why does std::numeric_limits::max() return 0?

后端 未结 2 1326
走了就别回头了
走了就别回头了 2021-02-07 04:49

I found an interesting gotcha with std::numeric_limits::max() returning 0. The answer is to use seconds::max() or std::numeric_lim

相关标签:
2条回答
  • 2021-02-07 05:22

    std::chrono::seconds itself is not a standard arithmetic type, thus std::numeric_limits is not specialized for it. So you just see some rather useless defaults.

    To query the range of the underlying type used to count the ticks (which, under gcc, is the 64 bit long int), use

    std::numeric_limits<seconds::rep>::max();
    

    instead.

    0 讨论(0)
  • 2021-02-07 05:25

    std::numeric_limits is not specialized for std::chrono::seconds. Default definitions are given for all data members and functions in std::numeric_limits to avoid compiler errors for unspecialized types. The default version of numeric_limits<T>::max() simply returns T(), which is 0 in this case.

    You can check if std::numeric_limits is specialized for a given T at compile time by checking std::numeric_limits<T>::is_specialized, which defaults to false.

    0 讨论(0)
提交回复
热议问题