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;
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;
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.
static_cast
eat and enum class
. - user194374static_cast
in brackets is not needed, and you have overloaded the prefix (++ m), but the postfix (m ++) is required - ampawdstatic_cast
will not work with the enum class
. - user194374Π£Π½Π°ΡΠ½ΡΠΉ ΠΏΡΠ΅ΡΠΈΠΊΡΠ½ΡΠΉ ΠΈΠ½ΠΊΡΠ΅ΠΌΠ΅Π½Ρ
. And is it binary? :) - αλΡΟΞΏΞ»Ο
Ο pmSource: https://ru.stackoverflow.com/questions/548354/
All Articles