One way is to cast the enum type to the underlaying type. This can be done with already defined std::underlying_type_t
to get the internal representation of the enum.
template < typename T>
auto toUnderlayingType( T t )
{
return static_cast<std::underlying_type_t< T >>( t );
}
template < typename T, typename U = std::underlying_type_t< T > >
void readToEnum( U u , T& t )
{
t = static_cast< T >( u );
}
class Y
{
public:
enum class X
{
ONE,
TWO
} x;
Y(): x{X::ONE} { }
void Print()
{
std::cout << toUnderlayingType(x) << std::endl;
}
void Read()
{
std::underlying_type_t< X > tmp;
std::cin >> tmp;
readToEnum( x, tmp );
}
};
int main()
{
Y y;
y.Print();
}
But in the case of serialization it is even better to use a better representation of content and data. As reflection is still not part of c++ you have to convert the enum value to any useful output and back. Maybe you will write text like "ONE" instead of 0 to the file. But all this is to broad for this answer. There are a long list of serializer libraries like boost and cerial
And you have to check if the incoming value is a valid one. Having the example above and assign a numerical 3 to it, the enum value is invalid. That topic is already discussed here:
What happens if you static_cast invalid value to enum class?