cpp-ru / ideas

Идеи по улучшению языка C++ для обсуждения
https://cpp-ru.github.io/proposals
Creative Commons Zero v1.0 Universal
89 stars 0 forks source link

enum_cast<> #512

Open Uriev opened 2 years ago

Uriev commented 2 years ago

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:

  1. During compile time it checks, if all enum's values are unique,
  2. At runtime it verifies, an incoming integer corresponds to the correct enum value, throwing std::bad_cast overwise.