tags:

views:

78

answers:

2

Hi, I have this:

typedef enum{
 Adjust_mode_None = 0,
 Adjust_mode_H_min,
 Adjust_mode_H_max,
 Adjust_mode_S_min,
 Adjust_mode_S_max,
 Adjust_mode_V_min,
 Adjust_mode_V_max
}Adjust_mode;

and at some point I want to do:

adjust_mode_ = (adjust_mode_+1)%7; 

but I get Invalid conversion from int to Adjust_mode

This is ok in other languages, what is wrong in C++? do I need to define some operator?

+4  A: 

use static_cast. You need an explicit conversion.

adjust_mode_ = static_cast<Adjust_mode>(adjust_mode_+1)%7;
aJ
Thanks, it worked! adjust_mode_ = static_cast<Adjust_mode> ((adjust_mode_ + 1)%7);
nacho4d
+2  A: 

Yes, you can define an operator...

Adjust_mode operator+(Adjust_mode lhs, int rhs)
{
    return static_cast<Adjust_mode>(
               (static_cast<int>(lhs) + rhs) % 7);
}

Adjust_mode operator+(int lhs, Adjust_mode rhs)
{
    return static_cast<Adjust_mode>(
               (lhs + static_cast<int>(rhs)) % 7);
}

Note that you need both to allow adjust_mode_ + 1 and 1 + adjust_mode_ to work. If you only provide a single function operator+(Adjust_mode, Adjust_mode) then either expression above would instead convert the enum to an int and return an int result.

This is pretty hackish, so you may be best off using a normal named function to perform the operation, rather than using an operator that can be too easily called by accident.

Tony