Maya wrote...
Quote
I am using an enum type that I want to store in a std::IOStream object,
but the compiler [complainer] tells me that the format is not supported.
enum types are the same as 'const int' right?
No, enumerations are types in their own right. You can implicitly
convert from an enumerator into its associated numeric value (which will
have an integral type, though it may or may not be int). However, you
*cannot* implicitly convert from an integer value to an enumerator,
which is what your example was effectively trying to do.
Instead, the easiest way to proceed is to read the value into a suitable
integral type, and then cast to the enumeration type, after performing
whatever sanity checks are appropriate on the value.
A better but more advanced technique is to provide a specific operator>>
to read from an istream into the enumeration type, which performs the
sanity checks itself and then either sets the enumeration value or sets
appropriate failure flags on the stream. This approach is much easier to
read and more robust, particularly if you do the smart thing and provide
a matching operator<< to output the enumeration type to an ostream.
Incidentally, you should be aware that outputting the enumerators as a
numerical value is a bit of a future-proofing hazard. If you ever
reorder the enumerators in the definition of the enumeration type, for
example by inserting a new value somewhere in the middle, your code will
still compile and run fine, but you'll break backward compatibility with
any existing data you've written out. For this reason, you might
consider it safer to have your << and>>operators store the enumerators
as well-defined strings, independently of their numerical values, rather
than just casting to/from an integer.
HTH,
Chris
{smallsort}