user5820174
user5820174

Reputation: 181

Using Enums instead of Hardcoded value

I have some code that detects which tab is selected in a QListWidget

int currentTab=ui->tabWidget->currentIndex();

if (currentTab==0)
     {
     // Code here
     }
else if (currentTab==1)
     {
    // Code here
     }
else if (currentTab==2)
     {
     // code here
     }
else if (currentTab==3)
     {
   // code here
     }

How do i use Enums instead of if(currentTab==0) or if(currentTab==1) or if(currentTab==2) or if(currentTab==3)

Upvotes: 0

Views: 1235

Answers (2)

Jeet
Jeet

Reputation: 1046

Example to use the Enums given below.
if you want to use same enum element in two enumerations, then you can use the enum classes (strongly typed enumerations) C++11.

#include <iostream>
#include <cstdint>

using namespace std;

//enumeration with type and size
enum class employee_tab : std::int8_t {
    first=0 /*default*/, second, third, last /*last tab*/
};

enum class employee_test : std::int16_t {
    first=10 /*start value*/, second, third, last /*last tab*/
};

enum class employee_name : char {
    first='F', middle='M', last='L'
};

int main(int argc, char** argv) {

    //int currentTab=ui->tabWidget->currentIndex();
    employee_tab currentTab = (employee_tab)1;
    switch (currentTab) {
        case employee_tab::first: //element with same name
            cout << "First tab Selected" << endl;
            break;
        case employee_tab::second:
            cout << "Second tab Selected" << endl;
            break;
        case employee_tab::third:
            cout << "Third tab Selected" << endl;
            break;
        case employee_tab::last: //element with same name
            cout << "Fourth tab Selected" << endl;
            break;
    }

    employee_name currentName = (employee_name)'F';
    switch (currentName) {
        case employee_name::first: //element with same name
            cout << "First Name Selected" << endl;
            break;
        case employee_name::middle:
            cout << "Middle Name Selected" << endl;
            break;
        case employee_name::last: //element with same name
            cout << "Last Name Selected" << endl;
            break;
    }

    return 0;
}

output:
Second tab Selected
First Name Selected

Upvotes: 0

vahancho
vahancho

Reputation: 21240

I would handle the same in the following way (with using an enum type):

enum Tabs {
    Tab1,
    Tab2,
    Tab3
};

void foo()
{
    int currentTab = ui->tabWidget->currentIndex();
    switch (currentTab) {
    case Tab1:
        // Handle the case
        break;
    case Tab2:
        // Handle the case
        break;
    case Tab3:
        // Handle the case
        break;
    default:
        // Handle all the rest cases.
        break;
    }
}

Upvotes: 6

Related Questions