3 ms·
What the alternative? Let’s say you have a file, you parse a uint32_t, and you want to convert that into the Handle type. If the enum is closed how do you do it
by zarzavat 2y ago
What the alternative? Let’s say you have a file, you parse a uint32_t, and you want to convert that into the Handle type. If the enum is closed how do you do it? Giant switch? That would break the fundamental principle that C++ abstractions are zero-cost.
- anonymoushn 2y agoI don't think that "abstractions are zero cost" necessarily applies to every serialization format you could choose to use, or to any other thing that isn't part of the language. 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.
- zarzavat 2y agoIt applies to the enum. If you couldn’t lift an integer into the enum without branching, then the enum isn’t zero cost - it requires more resources than C would to do the same thing. Bounds checking is never mandatory in C++. When C++ has broken this rule, developers have tended to turn those features off or ban them in style guides.
- anonymoushn 2y agoProviding exhaustive enums wouldn't prevent the language from providing non-exhaustive enums or users from placing values into them cheaply using memcpy.
- HelloNurse 2y agoWe could allow zero cost non-conversion from the primitive type (and invalid values at rest as a consequence) but check and complain about invalid enum values at runtime, "opt-in", when we care: in some kind of novel exhaustive pattern matching statement (not an old school switch statement), which can simply treat invalid values as an erroneous default case, or by invoking a synthesized validation method of the enum class (and if possible with validating variations of conversion from the primitive type, copy constructors and the like). 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.
- account42 2y agoYou either need that giant switch or checks at every use anyway in order to protect yourself against bad data. Better yet would be an explicit mapping of numbers in the file and enum values so that your file format and runtime enum are decoupled. The compiler can still optimize that into a simple range check when the values match up.