First, I wouldn't recommend you overload operator++
to have the enum cycle.
This could easily cause a hang if you have a loop like:
for( days d = MON; d <= SUN; d++ ) {
// hangs
}
It's really unexpected in C++ that operator++
cycles. Consider using a C++ function like this, so it's 100% clear from the code that the enum
will cycle
template <typename E>
inline E& cycleEnum( E &val, E minVal, E maxVal ) {
int e = (int)val;
if( ++e > maxVal )
e = minVal;
return val = (E)e;
}
Use:
days day = MON;
cycleEnum( day, MON, SUN );
Defining operator++ for enums
I have seen this done with a macro before
This only defines pre & post increment, but you could define bitwise ops too (though you probably shouldn't define increment and bitwise on the same enum class
)
#include <map>
#include <string>
using std::map, std::string;
enum class MouseButton {
Left,
Middle,
Right,
NUM_BUTTONS
};
#define PRE_AND_POST_INCREMENT( ENUM ) \
inline ENUM& operator++( ENUM& enumVal ) { \
return (ENUM&)(++(int&)enumVal); \
} \
\
inline ENUM operator++( ENUM& enumVal, int postIncrement ) { \
ENUM oldValue = enumVal; \
++enumVal; \
return oldValue; \
} \
PRE_AND_POST_INCREMENT( MouseButton )
map< MouseButton, string > mouseButtonName = {
{ MouseButton::Left, "Left" },
{ MouseButton::Middle, "Middle" },
{ MouseButton::Right, "Right" },
};
int main() {
for( MouseButton mb = MouseButton::Left; mb < MouseButton::NUM_BUTTONS; mb++ ) {
puts( mouseButtonName[ mb ].c_str() );
}
}
There is also this template
approach which you could adapt for operator++
(warning: it modifies all enum
s to act like an int
!)
static_cast<int>(d) + 1) % 7
to increment something, and what it that something? – Coumaronetypedef enum days {...} days;
is an exercise in redundancy. Just defineenum days {...};
. C++ doesn't require the same acrobatics as C to introduce the enum as a type. – Pentecostaloperator++
to cycle. Your app will hang if you do afor
loop likefor( days d = MON; d <= SUN; d++ )
. You should use a C++ function for something like that instead. – Polk