This conversion verifies incoming integer value against enum or enum class.
Purpose: Type-safe deserialization.
If we had an enum type, that implements some external specification, we would perform a complicated verification at the deserialization stage. There is no guarantee, that all enum values are consecutive, so only one overflow/underflow check + static_cast<> may be insufficient.
Let's take a look at an example:
enum stdcmd
{
run=0x10,
rerun=0x11,
stop=0x20,
// more values here
dbgcn=0xF1,
dbgdm=0xF2,
};
Here we should use switch-case deserialization or several overflow/underflow checking. Both implementations are clumsy and fragile (if the enum is changeable).
Therefore enum_cast simplifies the verification:
During compile time it checks, if all enum's values are unique,
At runtime it verifies, an incoming integer corresponds to the correct enum value, throwing std::bad_cast overwise.
This conversion verifies incoming integer value against enum or enum class. Purpose: Type-safe deserialization.
If we had an enum type, that implements some external specification, we would perform a complicated verification at the deserialization stage. There is no guarantee, that all enum values are consecutive, so only one overflow/underflow check + static_cast<> may be insufficient.
Let's take a look at an example: enum stdcmd { run=0x10, rerun=0x11, stop=0x20, // more values here dbgcn=0xF1, dbgdm=0xF2, }; Here we should use switch-case deserialization or several overflow/underflow checking. Both implementations are clumsy and fragile (if the enum is changeable).
Therefore enum_cast simplifies the verification: