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