-2

How can I properly make prefix and postfix operators for any type?

For example, I have this enum class:

enum class Traffic_light { green, yellow, red };

I try to create the operator overloads like:

Traffic_light operator++(int)
{
    return Traffic_light::green;
}


Traffic_light operator++()
{
    return Traffic_light::red;
}

But this does not work.

Traffic_light tl = Traffic_light::green;
++tl; // Error
tl++; // Error

error: no match for ‘operator++’

How does one overload operators in general?

I would like to see a general guide for any type.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tornikeo
  • 915
  • 5
  • 20
  • There are a number of questions that are closely related, but I'm not quite sure any are strictly duplicates. https://stackoverflow.com/questions/21295935/can-a-c-enum-class-have-methods and https://stackoverflow.com/questions/15450914/incrementation-and-decrementation-of-enum-class are enough to see that you can define these operators as non-member functions though. – BoBTFish Sep 03 '20 at 15:17
  • 1
    Those operators usually modify the relevant object and return either the new value (prefix) or the old (postfix). – molbdnilo Sep 03 '20 at 15:20
  • 1
    Why are you not actually incrementing but instead returning a specific value based on whether pre/postfix is valled? As for "I expect a general guide for any type", that's too broad and already answered in past questions. – underscore_d Sep 03 '20 at 15:30
  • *I expect a general guide for any type.* That's a pretty rude way of of phrasing your question. – super Sep 03 '20 at 15:39
  • @super sorry. I didn't mean to. Just reworded the last sentence. – tornikeo Sep 03 '20 at 17:10

2 Answers2

4

Since you need to make the operators non-member functions, you need to pass a Traffic_light argument to the operators:

Traffic_light operator++(Traffic_light const&, int)
{
    return Traffic_light::green;
}


Traffic_light operator++(Traffic_light const&)
{
    return Traffic_light::red;
}

Note that these are returning temporaries, and not references to a particular Traffic_light object, which is not how these operators are usually implemented.

Here's a demo.

cigien
  • 57,834
  • 11
  • 73
  • 112
1

You can do it like that

enum class Traffic_light { green, yellow, red };

Traffic_light& operator++(Traffic_light& t)
{
    if(t == Traffic_light::red)
        t = Traffic_light::green;
    else
        t = static_cast<Traffic_light>(static_cast<int>(t) + 1);
    return t;
}

Traffic_light operator++(Traffic_light& t, int)
{
    auto temp{t};
    ++t;
    return temp;
}

I have implemented it as cyclic. You can read the below link to get the overall information about operator overloading. For instance, which operators cannot be overloaded, etc.

Operator overloading

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Murat Hepeyiler
  • 430
  • 3
  • 12