C++ Logo


Advanced search

Re: Make non-specialized numeric_limits<T> use ill-formed

From: Jody Hagins <coachhagins_at_[hidden]>
Date: Fri, 10 Apr 2020 22:53:30 -0400
I believe it has been this way since the beginning. I don't like it either, BTW, but changing it could possibly break conforming programs that depend on the default values (especially is_specialized) so I doubt it is going to get much traction.

FWIW, the standard is very clear that std::numeric_limits only provides information about the implementation's representation of the arithmetic types. So, any type that is not arithmetic (like std::byte) will not have a specialization. While some books have shown examples of creating specializations for user defined types, creating any specialization for any type that is not an implementation representation of the arithmetic types is arguably undefined behavior.

You can always static_assert(std::numeric_limits<T>::is_specialized) to ensure a type is specialized before using it. Or, you can create your own NumericLimits that uses std::numeric_limits for any type where std::numeric_limits::is_specialized is true - and user provided specializations otherwise.

> On Apr 10, 2020, at 2:27 PM, Thomas Mercier via Std-Proposals <std-proposals_at_[hidden]> wrote:
> Hi,
> I encountered some surprising behavior from the std::numeric_limits<T> class template when experimenting with std::byte. The integer representation of the maximum std::byte value is 0 according to std::numeric_limits<std::byte>::max(). That is because there is no specialization of std::numeric_limits<T> for std::byte, because std::byte is not an arithmetic type. Ok, fine. But the fact that the program compiles, and produces an unexpected value is worrisome!
> The standard specifies that "The default numeric_­limits<T> template shall have all members, but with 0 or false values." (https://eel.is/c++draft/numeric.limits#3 <https://eel.is/c++draft/numeric.limits#3>)
> I would prefer to see this say something like, "a program which uses the default numeric_limits<T> template is ill-formed", so that an error is produced at compile time rather than a value initialized result (https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/limits#L321 <https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/limits#L321> and https://github.com/llvm/llvm-project/blob/master/libcxx/include/limits#L150 <https://github.com/llvm/llvm-project/blob/master/libcxx/include/limits#L150>).
> Does anyone know why the current wording specifies "0 or false values", or what any objections to my suggested change might be?
> https://godbolt.org/z/YVSECn <https://godbolt.org/z/YVSECn>
> Thanks,
> T.J.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2020-04-10 21:56:35