I have written a function template for serialization of enums to/from our stream class (Yes, I know boost::serialization, but it is not an option in my situation). Enums by convention in our company are serialized as int:
template<typename T>
Stream& operator<<( Stream& s, T const& value )
{
s << ( int ) value;
}
template<typename T>
Stream& operator>>( Stream& s, T & value )
{
int v;
s >> v;
value = (T) v;
}
These are simple templates, and they work nicely also in my function templates for (de)serializing a vector of enumeration items. I’m worried though that they are overly generic, i.e. that they get applied also for types T that are not enums but can be cast to/from an int. Can I improve the enum-serialization templates (or maybe the vector-serialization templates) to make sure they only apply to vectors of enums?
There are two improvements to be made here: not always serializing as
int(not all enums are), but as whatever the underlying type is. And, as your request, to only accept enums.The latter is easily solved with
std::enable_ifandstd::is_enum:And for the former, do the following inside the function:
This requires C++0x.
If that’s not an option, both
enable_ifandis_enumcan be found within Boost. However, I think you’ll need to makeunderlying_typeyourself. (And of course, in the worse case you can do all three yourself, thoughis_enumcan be a pain, if I recall correctly.)