When comparing enums that come from different sources such as those of the following code GCC emits warnings. Is there a way to avoid these warnings without c-style casts?
struct Enumerator
{
enum { VALUE = 5 };
};
template<int V>
struct TemplatedEnumerator
{
enum { VALUE = V };
};
if(Enumerator::VALUE == TemplatedEnumerator<5>::VALUE)
{
...
}
And GCC emits the following type of warning:
GCC: warning: comparison between 'enum ...' and 'enum ...'
I believe you can provide your own comparison operators, but you'll have to name the enums first:
struct Enumerator
{
enum Values { VALUE = 5 };
};
template<int V>
struct TemplatedEnumerator
{
enum Values { VALUE = V };
};
template <int V>
bool operator==(Enumerator::Values lhs, typename TemplatedEnumerator<V>::Values rhs)
{
return static_cast<int>(lhs) == static_cast<int>(rhs);
}
template <int V>
bool operator==(typename TemplatedEnumerator<V>::Values rhs, Enumerator::Values lhs)
{
return static_cast<int>(lhs) == static_cast<int>(rhs);
}
Interestingly Visual Studio doesn't actually warn about comparing the two enumerator types, but rather warns about a constant value in a if
statement - just like it will if you do this:
if (true) {...}
If there are N enums, won't there need to be N * (N - 1) comparison operators? That could end up being a lot.
Couldn't you just use the implicit conversion of enums to ints and do:
bool equals(int lhs, int rhs)
{
return lhs == rhs;
}
Then you can just do this in your code:
if(equals(Enumerator::VALUE, TemplatedEnumerator<5>::VALUE))
{
...
}
Also, you can check out enum-int casting: operator or function. The accepted answer says that you shouldn't use the implicit conversion, but a correctly named function like equals should make the code very readable and maintainable.
Don't do it.
The warning is there because you shouldn't mix up different enums in the first place.
For constants you can use a const declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With