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.
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*-1or something (the purpose ultimately is to avoid infinite recursion because-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 doenum_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
distancehas a converting constructor taking int (as indistance(int)), then given youroperator/the following is ambiguousFor this, maybe it’s better to make
field_typea 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’senum class, which provides strong enumerations.