• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 272
  • Last Modified:

Operator 0verloading

Having a thick morning today - its a monday!

Can you overload operators for enumerations eg:

enum enum1{ enum_list.....};
enum enum2{enum2_lsit.....};

bool operator<(enum1 lhs, enum2 rhs);

Or can you only overload where one of the operands is a class?
2 Solutions
Karl Heinz KremerCommented:
You can overload operators for enums. One example is listed in "The C++ Programming Language" (3rd edition) in 11.2.3 Operators and User-Defined Types.

Your example however would not work: You are comaring two different user defined types (enum1 and enum2). What you can do is:
bool operator<(enum1 lsh, enum1 rhs);

The compiler would not know how to convert your enum2 to an enum1 (or vice versa), so a comparison would not be possible. It's pretty much like comparing apples and oranges :-)


You can overload operators for DIFFERENT enums, too. The syntax is exactly as in the post above (see sample program below). The semantics, the meaning of comparing different enums, that is up to the programmer to provide. In the sample code below the macintosh apple is the king of fruit, less than no form of orange. The valencia orang is the trash of fruit, better than no apple. Then the others are compared by their underlying representations. _I_ gave the two this meaning and it is comparing apples and oranges.


For programmer convenience if you provide comparisons such as operator<(apple, orange) you should, symetrically, provide operator<(orange, apple).

Sample program:
#include <iostream>

using namespace std;

enum apples { macintosh, delicious, spy, ida_red, NUMBEROFAPPLES };
enum oranges { navel, blood, valencia, NUMBEROFORANGES };

string appleName[] = { "macintosh", "delicious", "spy", "ida_red", "" };
string orangeName[] = { "navel", "blood", "valencia", "" };

bool operator< ( const apples a, const oranges b)
  if (a == macintosh) return false;
  if (b == valencia) return true;
  return (int)a > int(b);

int main(int argc, char **argv)
  for(apples a = macintosh; a <= ida_red; ++a) {
    for (oranges o = navel; o <= valencia; ++o) {
      if (a < o)
        cout << appleName[a] << " < " << orangeName[o] << endl;
        cout << appleName[a] << " NOT < " << orangeName[o] << endl;
} /** End of main **/
mattjsimpsAuthor Commented:
well spotted. I do in fact want to compare two values of the same type. Told you it was a thick morning!

I am going to increase points to 130 and split 80:50 in bcladd's favour, since the answer answered what i asked.

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now