C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::next_higher, std::next_lower

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Sat, 07 Dec 2024 19:38:08 +0000
On 7 December 2024 16:26:52 GMT, Jonathan Wakely via Std-Proposals <std-proposals_at_[hidden]> wrote:
>On Sat, 7 Dec 2024, 15:24 Charles R Hogg via Std-Proposals, <
>std-proposals_at_[hidden]> wrote:
>
>> `std::nextafter` and friends provide the next representable value after
>> the first argument, in the direction of the second argument.
>>
>> Often, I find myself wanting specifically the next-higher or next-lower
>> representable value. In these cases, it feels awkward to cook up a number
>> that I know will be higher or lower. Yes, I can use
>> `std::numeric_limits`. I *think* `max` and `lowest` are the right tools
>> for the job. `infinity` is tempting, but I don't see a "negative infinity",
>>
>
>You just use -numeric_limits<T>::infinity()
>
>
>I don't want to raise questions in the reader's mind about negating
>> singular values like this, and `infinity` would be a disastrous choice for
>> integral types, where it returns `0`. (Not that we typically *intentionally
>> use* `nextafter` for integral types, but it may happen in a generic
>> template by accident.)
>>
>
>There is never a reason to use the numeric_limits<T>::infinity() value for
>the T in a generic function.
>
>nextafter takes a double for the 'to' argument so use
>±numeric_limits<double>::infinity().
>
>nexttoward is the same but takes a long double, so use ±numeric_limits<long
>double>::infinity().

As long as double and long double have infinity. Of course they have on most if not all platforms, but the standard doesn't guarantee that.

>
>That works even if the first argument is an integral type.
>
>You can also just use the HUGE_VAL and HUGE_VALL macros.
>
>
>
>> Sometimes I wonder: wouldn't it be more intent-based to provide something
>> like `std::next_higher()` and `std::next_lower()`, with a single argument?
>> Has this ever been proposed?
>>
>> Thanks,
>> Chip
>> --
>> Std-Proposals mailing list
>> Std-Proposals_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>>

Received on 2024-12-07 19:38:22