Is there a generic way to cast int to enum in C++?
If int falls in range of an enum it should return an enum value, otherwise throw an exception. Is there a way to write it generically? More than one enum type should be supported.
Background: I have an external enum type and no control over the source code. I’d like to store this value in a database and retrieve it.
The obvious thing is to annotate your enum:
You need the array to be kept up to date with
e, which is a nuisance if you’re not the author ofe. As Sjoerd says, it can probably be automated with any decent build system.In any case, you’re up against 7.2/6:
So if you aren’t the author of
e, you may or may not have a guarantee that valid values ofeactually appear in its definition.