Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a correct way to avoid warnings when comparing two different enums?

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 ...'
like image 749
Robert Gould Avatar asked Jan 28 '09 05:01

Robert Gould


3 Answers

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) {...}
like image 111
Eclipse Avatar answered Sep 27 '22 19:09

Eclipse


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.

like image 38
ZaDDaZ Avatar answered Sep 27 '22 21:09

ZaDDaZ


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.

like image 29
starblue Avatar answered Sep 27 '22 19:09

starblue