Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use std::max on enum types?

Tags:

c++

enums

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));
like image 788
Ben Jones Avatar asked Oct 16 '25 15:10

Ben Jones


1 Answers

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.