Overloading prefix operators ++/-- globally

36 views Asked by At

I can globally overload unary + and - operators like this:

#include <cstdint>

enum local_states_t
{
    LOCAL_STATE_A = 1,
    LOCAL_STATE_B,
    LOCAL_STATE_LIMIT,
};

typedef uint32_t state_type_t;

state_type_t operator-(local_states_t state) { return static_cast<state_type_t>(state | (1<<31)); }

Can I do the same for prefix ++/--? The problem here of course is how would the compiler know that it only needs to call these functions for local_state_t - types? Prefix operators don't have a dummy value..

1

There are 1 answers

0
MSalters On BEST ANSWER

(From the comments)

Yes - you can define local_states_t& operator++(local_states_t &). Unlike classes, enums can't have members, so you need a free function.

You can also define it to return state_type_t, which is unusual but allowed.