Say I have a class "Code" defined like this, with a user specified type conversion to int:
class Code
{
public:
int code;
std::string description;
Code (const int c, const std::string& d) : code(c), description(d) { ; }
operator int() const { return code; }
};
And a second class "Master" using the code class:
class Master
{
public:
Code master_code;
};
As well as a bunch of pre-specified codes, like this:
const Code CODE_ONE (1, "This is code one");
const Code CODE_TWO (2, "This is code two");
const Code CODE_THREE (3, "This is code three");
One would think (i.e. I would think) that one could use it like this:
Master master_obj;
switch (master_obj.master_code)
{
case CODE_ONE:
// ...
break;
case CODE_TWO:
// ...
break;
case CODE_THREE:
// ...
break;
default:
// ...
}
due to the automatic type conversion to int, but this is apparently not the case. GCC tells me that CODE_ONE, CODE_TWO and CODE_THREE "can not appear in a constant-expression".
This does not work either, by the way:
Master master_obj;
switch (master_obj.master_code)
{
case CODE_ONE.code:
// ...
break;
case CODE_TWO.code:
// ...
break;
case CODE_THREE.code:
// ...
break;
default:
// ...
}
The above returns the exact same error: "'CODE_ONE' can not appear in a constant-expression" in addition to a "'.' can not appear in a constant-expression".
But this does work:
Master master_obj;
switch (master_obj.master_code)
{
case 1:
// ...
break;
case 2:
// ...
break;
case 3:
// ...
break;
default:
// ...
}
So CODE_ONE etc. can't be resolved as constant expressions? That seems weird... Or am I doing something wrong?