Can I overload operators on enum types in C++?

c++, enums, operator-overloading

Solution

Yes, operator overloading can be done on enum and class types. The way you do it is fine, but you should use `+` to promote the enumeration, instead of `*-1` or something (the purpose ultimately is to avoid infinite recursion because `-t`):

inline foo operator -(field_type t) {
   return -+t;
}

This will scale well to other operations. `+` will promote the enumeration to an integer type that can represent its value, and then you can apply `-` without causing infinite recursion.

Notice that your `operator*` does only allow you to do `enum_type * integer`, but not the other way around. It may be worth considering the other direction too.

Also notice that it's always a bit dangerous to overload operators for operands that builtin-operators already accept (even if only by implicit conversions). Imagine that `distance` has a converting constructor taking int (as in `distance(int)`), then given your `operator/` the following is ambiguous

// ambiguous: operator/(int, int) (built-in) or
//            operator/(distance const&, field_type) ?
31 / month;

For this, maybe it's better to make `field_type` a real class with the appropriate operators, so that you can exclude any of such implicit conversions from begin on. Another good solution is provided by C++0x's `enum class`, which provides strong enumerations.

Problem

For example, if I have: ``` typedef enum { year, month, day } field_type; inline foo operator *(field_type t,int x) { return foo(f,x); } inline foo operator -(field_type t) { return t*-1; } int operator /(distance const &d,field_type v) { return d.in(v); } ``` Because if I do not define such operators it is actually legal to write `day*3` and it would be translated into 6? So is it legal? At least gcc and intel compiler accept this without a warning. Clearification: I do not want default arithmetic operations, I want my own operations that return non-integer type.

Original source