Overloading ++ operator for a scoped enum class type

时间:2015-07-28 16:07:32

标签: c++ enums operator-overloading

I've been experimenting with the enum class feature of c++ and successfully got the ++ operator to overload as follows:

enum class counter_t : uint8_t {VAL1 = 0, VAL2, VAL3, VAL4, END};

inline counter_t operator ++ (counter_t c, int) {
  counter_t c2;
  if (c == counter_t::END) {
  c2 = counter_t::VAL1;
    }
  else {
  c2 = (counter_t)((uint8_t)c + 1);
  }
  return (c2);
}

int main(void) {

  volatile counter_t x = counter_t::VAL1;
  x = x++;
  x++;

  while(1) {
    //do stuff
  }
}

Fairly straight forward. The "x=x++;" line works fine, however the "x++;" line does not. What is the correct form of the ++ operator function for the autoincrement version?

2 个答案:

答案 0 :(得分:3)

Just following the errors, the following code compiles runs and works fine on MSVC. Note the volatile and & in function parameters. Also c2 = c and a couple modifications, to follow the ++ standard (return value, then increment). volatile is necessary only because you have x declared as volatile.

inline counter_t operator ++ (volatile counter_t &c, int) 
{
    counter_t c2;

    if (c == counter_t::END)
        c2 = counter_t::VAL1;
    else
        c2 = static_cast<counter_t>(static_cast<uint8_t>(c) + 1);

    c = c2;

    return c2;
}

答案 1 :(得分:2)

You may use this to implement a prefix increment:

inline counter_t& operator ++ (counter_t& c) {
  if (c == counter_t::END)
      c = counter_t::VAL1;
  else
      c = counter_t(unsigned(c) + 1);
  return c;
}

Now, you can use the prefix increment to implement the postfix increment:

inline counter_t operator ++ (counter_t& c, int) {
  counter_t result = c;
  ++c;
  return result;
}

Test:

#include <iostream>
int main(void) {
    counter_t prefix = counter_t::VAL1;
    for(unsigned i = 0; i < 5; ++i)
        std::cout << unsigned(++prefix) << ' ';
    std::cout << '\n';

    counter_t postfix = counter_t::VAL1;
    for(unsigned i = 0; i < 5; ++i)
        std::cout << unsigned(postfix++) << ' ';
    std::cout << '\n';
}

Note: In each case the counter is taken by reference and gets modified.