On Tuesday, 27 September 2022 at 01:54:19 UTC, Steven Schveighoffer wrote:
> I misremembered how enums work in (old) C/C++. But it seems really awkward to make it difficult to extract the real value. I also don't see a huge harm in it implicitly converting, as D has allowed.
I suppose using namespaces and constexpr, one can almost mimic the behavior. But it's still not a type.
Hm, do you mean enums or constexpr? Constexpr constants are usually put inside a class. So you access them as ClassName::constant_name
. C++20 also allows accessing enums through the class scope by allowing the using
statement to apply to enums inside a class definition. So you can certainly build an enum like type with more advanced features than regular enums in C++. You can do it with enums, or without enums.
You can use enums to create new nominal integers. An example of this is std::byte which is defined like this:
enum class byte : unsigned char {} ;
As a result you cannot use operators on a byte
and you now have a type for unassuming octets. You can do this for your own integer-based type quite easily and define the operations you want.
> It seems the intuitive behavior is not readily accessible with C++.
The intuitive behaviour for an enumeration are the operations: comparison, successor, predecessor.
It gets a bit messier in C/C++ as you also tend to use it for bitsets. Which probably should be a different concept. Anyway, I've started to use enum class
for almost everything and then define overloaded set-functions that work on them. That way you encapsulate the casting and bit manipulation and hopefully get fewer bugs as a result.