C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::enum_max and std::enum_min

From: David Brown <david_at_[hidden]>
Date: Mon, 10 Jul 2023 17:44:54 +0200
On 10/07/2023 14:40, Alejandro Colomar via Std-Proposals wrote:
> Hi Jonathan,
>
> On 2023-07-10 13:28, Jonathan Wakely via Std-Proposals wrote:
>> On Mon, 10 Jul 2023 at 10:08, Sebastian Wittmeier via Std-Proposals <
>> std-proposals_at_[hidden]> wrote:
>>
>>> Hi Alex,
>>>
>>> I think you misunderstood.
>>>
>>> Jonathan's INT_MIN / INT_MAX do not return 1 or 16, respectively, for
>>> enums.
>>>
>>> Quite the opposite, Jonathan pointed out that the existing values INT_MIN
>>> / INT_MAX can be stored in MyEnum, so 1 or 16 are _not_ the minimum or
>>> maximum possible value for the example.
>>>
>>
>> Precisely.
>
>
> On 2023-07-10 10:02, Jonathan Wakely via Std-Proposals wrote:
>>> I propose that:
>>>
>>> std::enum_max<MyEnum>
>>>
>>> would evaluate to 16, and that:
>>>
>>> std::enum_min<MyEnum>
>>>
>>> would evaluate to 1.
>>>
>> Why?
>>
>> This is perfectly valid:
>> auto e = (MyEnum)INT_MAX;
>> And similarly for INT_MIN and 0 etc.
>
> This had confused me. I was like, is this some of this crazy magic
> that C++ has for enums to make them separate types from integers and
> I didn't know it? But no. :D
>
>
>> Any proposal related to the "min" and "max" of enums needs to
>> discuss the valid values of the enumeration type.
>
> [I'll talk about the C-compatible part, which is what I'm interested about;
> I don't really care about C++'s enum class and strong typing features]
>
> Regardless of the maximum and minimum values that are supported by the
> underlying type of an enum, it is always useful to be able to know 3 things
> of an enumeration:
>
> - Highest defined enumerator value.
> - Lowest defined enumerator value.
> - Count of enumerators in the enumerator list.
> - Are all the enumerators consecutive?
>

I agree on the first three. But I'm not sure an "are all the
enumerators consecutive?" query as being the right focus - I'd prefer a
way to declare enumerators where all the enumerators /must/ be
consecutive. However, I'd settle for a query that could be checked with
a static_assert.

I like stronger types. In C, enumerated types are not really types at
all - just aliases for "int". In C++, structured enumerated types are
much stronger, and therefore, to my tastes, a big improvement. But
there is still no way to have an enumerated type that will not allow
values other than the declared enumeration constants.

I'd also like sets from Pascal/Ada. That is, I think, a much nicer way
to handle flags than having them directly in an enumerated type. And
I'd like to copy the Pascal/Ada facilities for declaring arrays indexed
by an enumerated type. (Of course that can be done in C++ by defining
the [] operator for a class/template.)

I expect we'll be able to do all of this easily if/when metaclasses make
it to the standard.

Received on 2023-07-10 15:45:03