0

I have the following enum (which later will grow larger!):

enum TrainingFilters {
    NONE    = 0,
    GAUSS   = 1,
    SOBEL   = 2,
    FEATURE = 4
};

I have to print out string representation of the all possible combination. For now, a not-leangthy switch statement works fine, but if I add more items it will be disaster!

void Manager::setFilters(int filters)
{
    QString what("Selected filters:");

    switch (filters) {
    case 0:
        what.append(" NONE ");
        break;

    case 1:
        what.append(" GAUSS ");
        break;

    case 1 | 2:
        what.append(" GAUSS SOBEL ");
        break;

    case 2:
        what.append(" SOBEL ");
        break;
    case 2 | 4:
        what.append(" SOBEL FEATURE ");
        break;

    case 4:
        what.append(" FEATURE ");
        break;

    case 1 | 4:
        what.append(" GAUSS FEATURE ");
        break;

    case 1 | 2 | 4:
        what.append(" GAUSS SOBEL FEATURE ");
        break;

    default:
        qDebug() << "Invalid FILTERS enum received!";
        return;
    }

    qDebug() << what;
    mFilters = static_cast<TrainingFilters>(filters);
}

P.S: I have a few checkbox items in the user interface, and I should do some stuff according to the checked checkboxes. I use it like this:

var a, b,c;
cbGauss.checked ? a = 1 : a = 0;
cbSobel.checked ? b = 2 : b = 0;
cbFeat.checked ? c = 4 : c = 0;

cpManager.setFilters(a | b | c);

So my qustion is what is the best/easiest/smartest way to achieve this?

Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • Possible duplicate of [C++: Print out enum value as text](http://stackoverflow.com/questions/3342726/c-print-out-enum-value-as-text) – rbialon Dec 31 '15 at 19:06

1 Answers1

1

You could simply do

if (filters & 1)
    what.append("GAUSS ");
if (filters & 2)
    what.append("SOBEL ");
if (filters & 4)
    what.append("FILTER ");

And so on. This way you can easily add new ones. Of course you have to check for zero and then add NONE.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74