Is it possible to overload operators for enum enumeration type? If so, how?

I did not find a ban, but it did not work out.

I want to take and do, for example, like this:

 Mode t = UP; t++; /*ΠΈΠ»ΠΈ*/ t+=2; 
  • it is not very clear to overload the operators for the enum enumeration type. more detail please. - Senior Pomidor
  • @SeniorAutomator I want to take and do something like this: Mode t = UP; t ++; // or t + = 1; For this you need to overload the operator, how to do it? If possible - Xambey pm

1 answer 1

Can. Usually they do this:

 enum class Mode { UP, DOWN }; // ΠŸΡ€Π΅Ρ„ΠΈΠΊΡΠ½Ρ‹ΠΉ ΠΈΠ½ΠΊΡ€Π΅ΠΌΠ΅Π½Ρ‚. Mode& operator++(Mode& m) { m = static_cast<Mode>(static_cast<int>(m) + 1); return m; } // ΠŸΠΎΡΡ‚Ρ„ΠΈΠΊΡΠ½Ρ‹ΠΉ ΠΈΠ½ΠΊΡ€Π΅ΠΌΠ΅Π½Ρ‚. Mode operator++(Mode& m, int) { Mode old = m; m = static_cast<Mode>(static_cast<int>(m) + 1); return old; } // Π‘Π»ΠΎΠΆΠ΅Π½ΠΈΠ΅. Mode operator+(const Mode m, const int i) { return static_cast<Mode>(static_cast<int>(m) + i); } Mode operator+(const int i, const Mode m) { return operator+(m, i); } // Π’Ρ‹Ρ‡ΠΈΡ‚Π°Π½ΠΈΠ΅. Mode operator-(const Mode m, const int i) { return static_cast<Mode>(static_cast<int>(m) - i); } Mode operator-(const int i, const Mode m) { return operator-(m, i); } // Π‘Π»ΠΎΠΆΠ΅Π½ΠΈΠ΅ с присваиваниСм. Mode& operator+=(Mode& m, int i) { m = operator+(m, i); return m; } // Π’Ρ‹Ρ‡ΠΈΡ‚Π°Π½ΠΈΠ΅ с присваиваниСм. Mode& operator-=(Mode& m, int i) { m = operator-(m, i); return m; } 

If you use not the enum class , but the usual enum , then the internal static_cast can be removed.

  • Works great with the enum class . Another would be a semicolon to add. - αλΡχολυτ
  • BUT! For sure! static_cast eat and enum class . - user194374
  • in your example, the static_cast in brackets is not needed, and you have overloaded the prefix (++ m), but the postfix (m ++) is required - ampawd
  • @ampawd Without an internal static_cast will not work with the enum class . - user194374
  • Π£Π½Π°Ρ€Π½Ρ‹ΠΉ прСфиксный ΠΈΠ½ΠΊΡ€Π΅ΠΌΠ΅Π½Ρ‚ . And is it binary? :) - αλΡχολυτ pm