2

How can I use a struct to navigate a switch statement within a class member function?

I have a struct that contains data (uint8_t, unit16_t, int16_t, etc.) that I would like to use in a switch statement. What I originally prototyped in a scratch file does not work when I try to implement it within another class that needs to read this data.

Here is a generalized version of my C++ code:

struct toSwitch{
    const int one = 1;
    const int two = 2;
};

struct toSwitch{
    const int one = 1;
    const int two = 2;
};

class testClass{
public:
    void foo(){
        switch (temp) {
        case tosB.one:
            cout << "ONE" << endl;
            break;
        case tosB.two:
            cout << "TWO" << endl;
            break;
        default:
            break;
        }
    }
private:
    toSwitch tosB;
    int temp = 1;
};

int main()
{
    constexpr toSwitch tosA;
    int swTest= 1;

    switch (swTest) {
    case tosA.one:
        cout << "ONE" << endl;
        break;
    case tosA.two:
        cout << "TWO" << endl;
        break;
    default:
        break;
    }

    testClass b;
    b.foo();

    return 0;
}

In the main routine, the struct can be used to move through the switch statement as expected. (The output is "ONE".) However, I get compilation errors when I attempt the same statement within the testClass.

use of 'this' in a constant expression

'this' is not a constant expression

I have found a few useful links, but I do not fully understand yet. Why does making the structure a constexpr work in the main routine but not within the class?

Is there a way to initialize/force the data struct to be a constant expression for use in a switch statement?

Thanks!

[1] switch case: error: case label does not reduce to an integer constant

[2] C++: struct member in a switch statement

Mepix
  • 521
  • 1
  • 4
  • 15
  • 2
    In `toSwitch` definition, make it `static const int one = 1;` or `static constexpr int one = 1;`. Then in the `switch` statement, `case toSwitch::one:`. Drop `tosA` and `tosB`, you don't need them. – Igor Tandetnik Jun 26 '17 at 23:29
  • Thanks, that did the trick. – Mepix Jun 26 '17 at 23:39
  • 1
    Also consider making `toSwitch` an enum, as in `enum class toSwitch { one=1, two=2};` Used the same way, `case toSwitch::one:` – Igor Tandetnik Jun 27 '17 at 00:29

0 Answers0