Why Is This Expression Resulting In an Integer?

closed account (zb0S216C)
I have this expression, which attempts to remove a set flag:

 
Flags &= (~FLAG_LOCKED);

Where "Flags" is of type "Flag", and "FLAG_LOCKED" is part of the enumeration list, "Flag":

1
2
3
4
5
enum Flag 
{
    FLAG_LOCKED = (1 << 0),
    // ...
} Flags;

For some reason, the left-hand operand of the assignment is returning an "int", and not a "Flag" enumerator. Why is this? and how can I overcome this? I tried casting the result of the negation to a "Flag" enumerator, but it still gave the same error.

Here's the error:

Compiler wrote:
"error: invalid conversion from 'int' to 'Flag'"

Thanks :)

Wazzak
Last edited on
FLAG_LOCKED is of type int. That is just how enum works.
You could do this to fix that:
Flags &= static_cast< Flag >( ~FLAG_LOCKED );
Last edited on
If you were able to do that, it could not be guaranteed that the value of Flags was set to one of the valid enum values (FLAG_LOCKED, etc.). Why not make Flags to an (unsigned) integer type?
closed account (zb0S216C)
@kevinkjt2000: As I said, I tried casting the result of the negation to a "Flag" enumerator, but the compiler wouldn't allow it; it gave the same error. However, enumerators are not always of type "int", because the underlying type is implementation-defined (though, the type must be integral).

@Peter87: Hmmmmm... using "unsigned" isn't that bad of an idea, and it may only be the only choice I have right now. I'll leave this thread open a bit longer to see if anyone suggests anything else.

Thanks for the replies :)

Wazzak
The compiler shall issue an error because there is no overloaded operator &= for the enumeration type.
You can overload this operator for your enumeration. For example

1
2
3
4
5
6
7
8
9
10
11
enum X { x, y };
X & operator &=( X &lhs, int rhs )
{
	return ( lhs = static_cast<X>( lhs & rhs ) );
}

int main()
{
	X a = X::y;
	a &= ~X::y;
}

Last edited on
closed account (zb0S216C)
Never mind, lads. I ended up implementing a structure which holds static constants which represent the bit masks, overloads the bitwise operators, and so forth. So far it works as expected. In fact, it works better than an enumeration list.

Thanks for the suggestions, though :)

Wazzak
Topic archived. No new replies allowed.