C++ Logo

std-proposals

Advanced search

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

From: Dominic Fandrey <isocpp.id_at_[hidden]>
Date: Tue, 11 Jul 2023 10:46:58 +0200
I would suggest a more generic approach, e.g. variadic expansion for enums.

On 10/07/2023 09:15, Frederick Virchanza Gotham via Std-Proposals wrote:
> Given the following enum:
>
> enum MyEnum : int {
> eInvalid = 1,
> eFrog = 2,
> eGoat = 4,
> eFish = 8,
> eMonkey = 16,
> };

Consider the possibilities of `MyEnum...` expanding into each individual value:

~~~
#include <algorithm>
constexpr auto min(MyEnum v) { return v; }
constexpr auto min(MyEnum head, auto... tail) {
     using std::min;
     return static_cast<MyEnum>(min(static_cast<int>(head), static_cast<int>(min(tail...))));
}
static_assert(MyEnum::eInvalid == min(MyEnum...));
~~~

You can test that code right now, the only thing you have to change is doing the
expansion in the static_assert manually.

And of course you can implement generic versions using <type_traits> and <concepts>,
but I wanted to keep the code simple.

> I propose that:
>
> std::enum_max<MyEnum>
>
> would evaluate to 16, and that:
>
> std::enum_min<MyEnum>
>
> would evaluate to 1.

Received on 2023-07-11 08:47:01