How to input from stream to enum type?
I can do it so
unsigned int sex = 0;
stream >> sex;
student.m_bio.sex = static_cast<Sex>(sex);
Otherwise?
How to input from stream to enum type?
I can do it so
unsigned int sex = 0;
stream >> sex;
student.m_bio.sex = static_cast<Sex>(sex);
Otherwise?
This question was asked in a more general form over here: How to read enums from a std::istream in a generic fashion. The OP almost had a working solution as it was; he just had some trouble with
const
, and a few unnecessary angle-brackets. Here's the working solution fleshed out:The
read_enum
function template serves the same purpose here asstd::make_pair
orstd::make_shared
in the standard library: it lets us dispense with the angle brackets. You could equally well writein >> EnumReader<enSide>(val.mSide) >> EnumReader<enType>(val.mType)
, but that's more typing (pun intended).A few vendors' standard libraries are allegedly still missing
std::underlying_type
from their<type_traits>
headers. If you have one of these incomplete libraries, you can use one of the workarounds listed at How to know underlying type of class enum?.This is not pretty but should do it
Cheers, CC
If you want to ensure that the value is valid, you can do something like this: