The following is a typical situation in our codebase.
enum ConfigOption { CONFIG_1=1, CONFIG_2=2, CONFIG_3=3 }
ConfigOption cfg1, cfg2;
sscanf(s, "%d", &cfg1);
This is an internally used simulation software. Not distributed. Ease of maintenance and correctness are important. Portability and user interface -- not really.
The trouble is enum
in C++ is not necessarily an int
. So we get a compiler warning, and may get incorrect behavior when using a different compiler or when optimizations are enabled.
One solution is just to cast &cfg
to int*
. However this will not catch cases where the compiler had decided to allocate something other than int
to the enum
.
So I suggested the following solution:
template<typename T> inline
int& eint(T& enum_var) {
assert(sizeof(T) == sizeof(int));
return (int&)enum_var;
}
And now one uses scanf
as follows:
sscanf(s, "%d", &eint(cfg1));
I would love to hear opinions and other (better) solutions to the above problem. Keep in mind that one of the goals is to keep the code simple. This is not 'production-quality' stuff and the more you add -- the more difficult maintenance becomes.