C++ Logo

std-proposals

Advanced search

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

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Mon, 10 Jul 2023 12:25:28 +0100
On Mon, 10 Jul 2023 at 09:53, Alejandro Colomar <alx.mailinglists_at_[hidden]>
wrote:

> Hi Jonathan!
>
> On Mon, Jul 10, 2023, 10:03 Jonathan Wakely via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>>
>>
>> On Mon, 10 Jul 2023, 08:15 Frederick Virchanza Gotham via Std-Proposals, <
>> std-proposals_at_[hidden]> wrote:
>>
>>> Given the following enum:
>>>
>>> enum MyEnum : int {
>>> eInvalid = 1,
>>> eFrog = 2,
>>> eGoat = 4,
>>> eFish = 8,
>>> eMonkey = 16,
>>> };
>>>
>>> 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.
>>
>
> Heh, I learnt something new today. I didn't know about this. Would you
> mind pointing to where this feature is described in the standard? I'm
> curious about it.
>

Which feature? This is just casting an integer to an enumeration type,
which is valid in C and C++. I assume you mean the fact that all values
from [INT_MIN, INT_MAX] are valid values of the enumeration type?
That's [dcl.enum] p8: "For an enumeration whose underlying type is fixed,
the values of the enumeration are the values of the underlying type."



> Regarding the proposal, I find it more readable and portable, since
> casting to an enum type in C doesn't do that magic.
>

There's no magic here at all, I don't know what you mean. The code above
does exactly the same in C and C++, as far as I understand.
C2x CD2 seems to have very similar semantics for an enumeration type with a
fixed underlying type, according to 6.7.2.2 p15.



> But since the feature already exists, I wouldn't support yet another way
> of doing the same thing.
>
> At the very least, I'd use this cast always within a template or macro
> called to_enum<type>(value) or to_enum(type, value). But probably in a
> project-defined one, and not a standard one.
>

Really? You would not write this and expect it to work?

enum Bits { one = 1, two = 2, four = 4 };
Bits b = (Bits)(one | four);

Or just (Bits)0 where there isn't an enumerator with that value?

C and C++ require the underlying type to be able to represent

Enums can take values that don't correspond to an enumerator, that's a fact
in both C and C++, and proposals about valid values of the enumeration type
always seem to be written as though that isn't true.

Received on 2023-07-10 11:25:42