Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 894
Artyom Avatar asked Mar 06 '10 17:03

Artyom


People also ask

Can you overload an enum?

To explicitly answer your question, no that is not possible. The constants can not be represented as datatypes. Show activity on this post. First of all, java doesn't have runtime method overloading.

Which operator we Cannot overload in C?

Detailed Solution. (::) Scope resolution operator cannot be overloaded in C language. Operator overloading:- It is polymorphism in which an operator is overloaded to give user-defined meaning to it. The overloaded operator is used to perform operations on user define data type.

Can you overload the operator for data type int?

No we cannot overload integer or float types because overloading means to change the working of existing operators or make them to work with objects int is single member not an object.


1 Answers

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.

like image 194
Johannes Schaub - litb Avatar answered Sep 25 '22 20:09

Johannes Schaub - litb