I have two enum
objects a
and b
, and I would like to get the max of the two. Here is what I have:
enum MyEnum {
ZERO,
ONE,
TWO,
THREE
};
MyEnum max_val = std::max(TWO, THREE);
This works fine on my machine (max_val is assigned the value of THREE). However, I want to know if this is good practice, or if it would be better to cast to int
to do any comparison operations, like so:
MyEnum max_val = static_cast<MyEnum>(std::max<int>(TWO, THREE));
You don't need the static_cast
- this is perfectly OK:
#include <algorithm>
enum MyEnum {
ZERO,
ONE,
TWO,
THREE
};
MyEnum e = std::max( ZERO, ONE);
Requirements for std::max
are at https://en.cppreference.com/w/cpp/algorithm/max - values must be comparable and copy-constructible, which enum values are.
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