Consider the following code:
enum TestEnum
{
TEST_ENUM_5 = 5
};
class Test
{
public:
Test() { mType = TEST_ENUM_5; mVal = 1; }
TestEnum& type() { return (TestEnum&)mType; }
private:
uint16_t mType;
uint16_t mVal;
};
int main( int argc, const char* argv[] )
{
Test test;
assert( test.type() == TEST_ENUM_5 );
}
The program compiles fine with MSVC 2010 – no errors or warnings. But the assertion fails – the value returned is not 5 but rather 0x00010005.
In other words the value of the returned enumeration is interpreted as a 4 byte value – including the contents of the following short. I can see why the compiler is doing this, the reference is a ref to the address of mType, and a register is being loaded with the next 4 bytes.
But is this correct behavior for the compiler?
Shouldn’t it know that TestEnum& is a reference to a 16-bit quantity? Or if it doesn’t want to do that, shouldn’t it warn?
That aside, what I’d like to do is store a short enumeration into a 16 bit value, and have method that returns a reference to it, that is typed as that typedef. That is logically what I want is an interface that allows me to:
test.type() = TEST_ENUM_5;
And have it know at compile time that only values from TestEnum are expected. For that matter I want users of the class when they read it to know TestEnum values are expected here.
You say that the enum has to be two bytes, and that the return type of
type()has to be an enum reference.C++11 has a feature whereby you can specify the underlying type of an enumeration: