In my class I defined an enum like this:
class myClass
{
public:
enum access {
forL,
forM,
forA
};
typedef access AccessType;
I just had same issue. i have to initialize an object from what i read in an xml file and for sure, i have no control over what could happen to that file.
Constructor has an enum as argument :
enum status_t { NOT_STARTED, STARTED, DONE };
MyObject::MyObject(int id, status_t status) : m_id(id), m_status(status){}
So when parsing the Xml i have to cast it. I prefered then to handle the cast in the constructor so the other classes do not have to know which is the valid enums.
MyObject::MyObject(int id, int status) : m_id(id){
m_status = status_t(status);
}
But no way to be sure the value coming from xml will be in the correct range.
Here is the solution i came with :
MyObject::MyObject(int id, int status) : m_id(id){
switch(status){
case NOT_STARTED:
case STARTED:
case DONE:
m_status=status_t(status);
break;
default:
m_status=NOT_STARTED;
break;
}
}
This is an implementation choice, to force a default value in case of non consistent data. One could prefer throwing out an exception, in my case it will do this way.