Much of the code in place at the company I work for frequently uses unsigned char types for small numbers to avoid unwanted padding in data structures. I rarely see a problem with this, however I ran into a small issue with implicit conversion while setting error flags with bitwise operators. I found a workaround by simply being explicit, but I was wondering if there was a more elegant way. Btw we compile with c++11
Given the error code enum below:
enum ErrorType : unsigned char
{
OK. = 0x00,
ERROR01 = 0x01,
ERROR02 = 0x02
};
and assuming I have some classes with private members of type errorType which will use public members to set or unset flags, for example:
struct S
{
public:
void setError1();
void unsetError1();
private:
ErrorType errorType;
};
If I try to set values implicitly live below:
void S::setError1()
{
this->errorType |= ERROR01;
}
I get type conversion errors
however if I explicitly cast the bitwise conversion it works
this->errorType = ErrorType(this->errorType | ERROR01);
It would appear that the problem is that the output of bitwise conversions is always an integer and does not necessarily reflect the input type. Is this true? and if so is there a way to specify a type for it so I don't have to explicitly cast every time?
Aucun commentaire:
Enregistrer un commentaire