Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to define operators for enums? For example I have enum Month in my class and I would like to be able to write ++my_month.
Thanks
P.S.
In order to avoid overflowing I did something like this:

void Date::add_month()
{
    switch(my_month_)
    {
    case Dec:
        my_month_ = Jan;
        add_year();
        break;
    default:
        ++my_month_;
        break;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
257 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes, you can:

enum Month
{
  January,
  February,
  // ... snip ...
  December
};

// prefix (++my_month)
Month& operator++(Month& orig)
{
  orig = static_cast<Month>(orig + 1); // static_cast required because enum + int -> int
  //!!!!!!!!!!!
  // TODO : See rest of answer below
  //!!!!!!!!!!!
  return orig;
}

// postfix (my_month++)
Month operator++(Month& orig, int)
{
  Month rVal = orig;
  ++orig;
  return rVal;
}

However, you have to make a decision about how to handle "overflowing" your enum. If my_month is equal to December, and you execute the statement ++my_month, my_month will still become numerically equivalent to December + 1 and have no corresponding named value in the enum. If you choose to allow this you have to assume that instances of the enum could be out of bounds. If you choose to check for orig == December before you increment it, you can wrap the value back to January and eliminate this concern. Then, however, you've lost the information that you've rolled-over into a new year.

The implementation (or lack thereof) of the TODO section is going to depend heavily on your individual use case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...