C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Using -1 as the max value for an unsigned integer

From: Ted Lyngmo <ted_at_[hidden]>
Date: Mon, 18 Aug 2025 19:49:06 +0200
Sorry for spamming, but here's an updated version of the `_Max` idea:

```
template<class T>
concept arithmetic = (std::integral<T> or std::floating_point<T>);

inline constexpr struct max_type final {} _Max;

constexpr bool operator<=>(max_type, arithmetic auto other) {
     return std::numeric_limits<decltype(other)>::max() <=> other;
}
constexpr bool operator==(max_type, arithmetic auto other) {
     return std::numeric_limits<decltype(other)>::max() == other;
}
```

/Ted

Den 2025-08-18 kl. 19:17, skrev Ted Lyngmo:
> Den 2025-07-18 kl. 11:15, skrev Frederick Virchanza Gotham via Std-
> Proposals:
>> And it's annoying when a compiler emits a warning for "-1 == n" to say
>> that I'm comparing signed with unsigned.
>>
>> I wonder could we standardise some shorthand for this?
>
> `if (n == -1uz)` - but MSVC warns about that.
>
> Another way that you could define yourself (except you shouldn't use a
> reserved identifier):
> ```
> inline constexpr struct {} _Max;
>
> template <class T>
> constexpr auto operator<=>(decltype(_Max), T other) {
> return std::numeric_limits<T>::max() <=> other;
> }
> template <class T>
> constexpr bool operator==(decltype(_Max), T other) {
> return std::numeric_limits<T>::max() == other;
> }
> ```
> But I don't really see a compelling reason _not_ to use `npos` which is
> defined specifically for this situation. Sure, `_Max` is shorter, but
> still.
>
> Br,
> Ted
>

Received on 2025-08-18 17:49:10