Is there a way to specify the default constructor of an enum class
?
I am using an enum class
to specify a set of values which are allowable for a particular datatype in a library: in this case, it's the GPIO pin id numbers of a Raspberry Pi. It looks something like this:
enum class PinID : int {N4 = 4, N17 = 17, /* ...etc... */ }
The point of me doing this instead just of using, say, an int
is to ensure that code is safe: I can static_assert
(or otherwise compile-time ensure -- the actual method used is not important to me) things like that someone hasn't made a spelling error (passing a 5 instead of a 4, etc), and I get automatic error messages for type mismatches, etc.
The problem then is that enum class
has a default constructor that -- for compatibility's sake with C's enum
s I assume (since they have the same behaviour) -- initializes to the enum class
equivalent of 0
. In this case, there is no 0
value. This means that a user making a declaration/definition like:
PinID pid = PinID();
is getting an enumerator that isn't explicitly defined (and doesn't even seem to "exist" when one looks at the code), and can lead to runtime errors. This also means that techniques like switch
ing over the values of explicitly defined enumerators is impossible without having an error/default case -- something I want to avoid, since it forces me to either throw
or do something like return a boost::optional
, which are less amenable to static analysis.
I tried to define a default constructor to no avail. I (desperately) tried to define a function which shares the name of the enum class
, but this (rather unsurprisingly) resulted in strange compiler errors. I want to retain the ability to cast the enum class
to int
, with all N#
enumerators mapping to their respective #
, so merely "defining", say, N4 = 0 is unacceptable; this is for simplicity and sanity.
I guess my question is two-fold: is there a way to get the kind of static safety I'm after using enum class
? If not, what other possibilities would one prefer? What I want is something which:
- is default constructable
- can be made to default construct to an arbitrary valid value
- provides the "finite set of specified" values afforded by
enum class
es - is at least as type safe as an
enum class
- (preferably) doesn't involve runtime polymorphism
The reason I want default constructability is because I plan to use boost::lexical_cast
to reduce the syntactic overhead involved in conversions between the enum class
values, and the actual associated string
s which I output to the operating system (sysfs in this case); boost::lexical_cast
requires default constructability.
Errors in my reasoning are welcome -- I am beginning to suspect that enum class
es are the right object for the wrong job, in this case; clarification will be offered if asked. Thank you for your time.