by lpribis · 2y ago · 0 comments
enum class Handle : uint32_t { Invalid = 0 };
Handle h { 42 }; // OK
One of their examples demonstrates the number one issue for me with enums, which was not fixed with `enum class`. Since values outside the range of the type are valid, you are constantly needing to check for invalid values in any function that takes an enum [class]. Ruins any attempt at "parse, don't validate" style in c++ and completely ruins the "type safety" which c++ people are always going on about.Then you find out that members of a "variant" are not really variant members but just the individual types that can be assigned to a union. For example, assigning to a non-const reference does not work (and obviously cannot work once you realize that std::variant is just syntax sugar over a tagged union).
Most of these new additions since C++11 are just leaky abstractions and wrappers.
It would be easy to make it work, there isn't necessarily a strict relation between the template parameter and the actual stored object. Not having reference variant members was a conscious decision, same as optional<T&>. Hopefully this will be fixed in the future.
I personally would have liked to see recursive variant types and multi-visitation (as supported by boost::variant).
# type foo = Int of { n : int } | Float of { f : float };;
type foo = Int of { n : int; } | Float of { f : float; }
# Int { n = 10 };;
- : foo = Int {n = 10}
# let r = ref (Int { n = 10 });;
val r : foo ref = {contents = Int {n = 10}}
Notice that the constructor Int { n = 10 } automatically produces a foo type and assigning to a mutable ref works.The same in C++, using assignment to a pointer to avoid the lvalue ref error that is irrelevant to this discussion:
#include <variant>
struct myint {
int n;
myint(int n) : n(n) {}
};
struct myfloat {
float f;
myfloat(float f) : f(f) {}
};
using foo = std::variant<myint, myfloat>;
int
main()
{
const foo& x = myint{10}; // works
foo *z = new myint{10}; // error: cannot convert ‘myint*’ to ‘foo*
}
As stated above, this obviously cannot work since C++ has no way of specifying a myint constructor that -- like in OCaml -- automatically produces the variant type foo.C++ would need true algebraic data types with compiler support (that would hopefully be as fast as switch statements). To be useful, they would need a nice syntax and not some hypothetical abomination like:
using foo = std::variant<myint, myfloat> where
struct myint of foo { ... }; std::variant<int&, etc>
does not work well.https://schneide.blog/2018/01/11/c17-the-two-line-visitor-ex...
variants are a such disappointment at every step of trying to use them
template<E>
std::optional<E>
from_underlying(std::underlying_type<E>)
requires(std::is_enum_v<E>)This is valid code in C++11:
enum class Foo : int { Invalid = 0 };
Foo f = Foo(5);
In C++11, this compiles with Foo(5) but not Foo{5}. In C++17, this compiles with both Foo(5) and Foo{5}.Making it UB for enum classes was considered, but the strongly typeded alias use case was considered safer and more useful.
enum Event<T> {
System(SystemEvent),
User(T),
}Anyway, the point of what gp describes is to do this in a single integer without overhead so a naive sum type is not the solution.
Is it possible to override the constructor so it limits the allowed values? Implement other methods on the `enum class`? If so then that makes them still very useful, albeit not in the usual `enum` sense.
They indeed are. I find myself using enums classes as strong typedefs more often than actual enums.
You can easily build your own safe enum on top of you really want.
Edit: someone else pointed out the bitmask use case else thread. Strongly typed integrals is also a common use case.
If you could do:
my_enum_type foo(std::vector<char>& buf, int& offset)
{
// bounds check omitted for brevity
// return my_enum_type{buf{offset++]}; // outside an unsafe-style block would cause a compile error, or a throwing constructor. TBD
std::unsafe {
return my_enum_type{buf[offset++]};
}
}
you would reduce the possible impact areas to places where you explicitly want to do dangerous stuff.Instead we end up with a feature that is a "zero cost abstraction" which just pushes the bookkeeping onto the user - every switch statemeent needs to handle the case where someone has passed in 42.
1. make invalid values UB.
2. make invalid values non-representable by enforcing checks.
3. enum class is just a strong integer typedef with named constants.
Luckily 1 was reject: already too much UB. 2 would require runtime checking and was not considred viable by many; also it would prevent a lot of useful cases. 3 was the remaining option and was consistent with existing enum usage.
Bitmask enums are also a hack and the better solution is to have different types for the individual flags (an enum) as well as a type for combinations of flags (custom type built around an integer).
Yes, these are existing uses but when enum class was designed there were no existing usages for that.
> but when enum class was designed there were no existing usages for that.
IIRC diverging from standard enum was considred, but rejected as deemed a surprising change in behaviour.
The reason other values of the underlying integral type beyond the named ones are allowed, is that enums are often used to specify bit values or bit masks that you AND/OR with each other. It is what it is.
The other question is, how would you go about converting an integral value to an enum type if only specific values were allowed? Either you need an explicit case distinction (potentially large switch) for all the allowed values, or there would have to be a hidden structure/array specifying the valid values at runtime, generated by the compiler. C++ is rather conservative in adding such runtime structures.
Except bitwise operations of orign enum values yields the underlying type and not an enum value. And for enum classes the operators don't exist at all. So you need to write custom operators(or manual casts) for this use case anyway so you might as well go all the way and write a proper typed bitset type instead of abusing enums. Allowing this for old enums makes sense for C compat but that doesn't mean enum class couldn't have been stricter.
False:
enum Foo { foo, bar };
auto x = foo|bar;
static_assert(std::is_same_v<decltype(foo), Foo>);
edit: I'm wrong, see below.Most enum use is served adequately by never letting in potentially invalid values from untrusted input; an enum variable that is set to an enum constant will necessarily have a valid value. "Decayed" primitive values, like a bitmask formed by bitwise operations between valid enum values, aren't normally intended to be re-ingested as enum values.
If you want to guarantee that some value is within the allowed range of values, normally you'd have to run some code to do that, yes.
When C++ has broken this rule, developers have tended to turn those features off or ban them in style guides.
Even if under the covers an enum is/was implemented as a special class, why would the language syntax leak this implementation detail to the programmer?
Perhaps it would be cleaner to make enum its own concept, rather than trying to shoehorn it into classes. It is a fundamentally different thing than a class after all. Is there a reason, why this is not done?
So enum and class were two existing keywords whereas scoped would be a new keyword.
There's also a sentiment among C++ proponents that classes (a user defined product type with implementation inheritance) are all you really need anyway.