Open tsoj opened 1 month ago
I like the idea... but maybe the syntax should be get_underlying and set_underlying ... possibly value as well, so we don't deviate so much from how people are used to using enums and enum classes, where currently you have to cast from/to std::underlying_type_t
I'm curious how others feel about this as well.
In my opinion, to get the raw value we should just be able to cast, for example, by saying s as u8
. To set the raw value, we probably should have a escape hatch yes, but I would like this escape hatch to come both in checked and unchecked flavors, I think maybe a pre-condition that can be optimized away could be good to cover both cases with a single function / constructor.
In my opinion, to get the raw value we should just be able to cast, for example, by saying
s as u8
. To set the raw value, we probably should have a escape hatch yes, but I would like this escape hatch to come both in checked and unchecked flavors, I think maybe a pre-condition that can be optimized away could be good to cover both cases with a single function / constructor.
Being able to get the raw value with as
is my suggestion #816, though I would leave the existing get_raw_value
method for the pure readability of the thing. And @gregmarr was working on it as part of a larger refactor of as
(#701, I think), but that effort seems to have stalled.
My sense is that as
was meant to be always safe, so using it for type conversion to @enum
type would have to be checked.
My sense is that as was meant to be always safe, so using it for type conversion to @enum type would have to be checked.
It is always safe to get the underlying value, so the as
cast should be safe. The other way around (u8
-> @enum
) wouldn't be a cast, but a explicit constructor or a static member function that acts as a constructor.
And @gregmarr was working on it
Not me, sorry.
And @gregmarr was working on it
Not me, sorry.
Apologies.
In case I didn't miss anything, it is currently not possible to create an enum instance from a raw integer.
If the values of enum instances should matter at all (which is suggested by the possibility to assign custom values to specific enum members, and by the existence of
get_raw_value()
), then I believe it should also be possible to create an enum instance from an integer.A specific use case I have in mind:
Ways to make something like this possible could be:
operator= : (implicit out this, _val: i64)
public.Square::from_raw_value(val: i64)
) to make clear that converting an integer into an enum is an unusual/dangerous operation