portable code and enums of various sizes

S

Simon Elliott

I have some legacy C++ code which requires some enums to be 1 or 2
bytes in size.

I'd ideally like to be able to specify that a few carefully selected
enums are a particular size.

By default, g++ seems to create enums of 4 bytes in length, unless I
use the -fshort-enums option. I don't much want to use this all or
nothing approach in case it breaks library code etc, and there's no
guarantee that other compilers have a comparable option in any case.

I could of course replace the enums with unsigned char or unsigned
shorts, but I wonder if there's a more elegant C++ solution, Is there
any way I can create a class containing an unsigned char or unsigned
short, but with the semantics of an enum?
 
E

Earl Purple

Simon said:
I have some legacy C++ code which requires some enums to be 1 or 2
bytes in size.

I'd ideally like to be able to specify that a few carefully selected
enums are a particular size.

By default, g++ seems to create enums of 4 bytes in length, unless I
use the -fshort-enums option. I don't much want to use this all or
nothing approach in case it breaks library code etc, and there's no
guarantee that other compilers have a comparable option in any case.

I could of course replace the enums with unsigned char or unsigned
shorts, but I wonder if there's a more elegant C++ solution, Is there
any way I can create a class containing an unsigned char or unsigned
short, but with the semantics of an enum?

Well you could use const char and const short variables in a header
file.
Alternatively keep them as enums (ensuring they fit into the values)
and in your class contain 1 or 2 byte variables to hold their numeric
equivalents. You can still switch on them using the enum names.
 
S

Simon Elliott

Well you could use const char and const short variables in a header
file.
Alternatively keep them as enums (ensuring they fit into the values)
and in your class contain 1 or 2 byte variables to hold their numeric
equivalents. You can still switch on them using the enum names.

Yes. I did the latter as its simple and allows us to keep the enum
constants which are useful for type safety in function calls.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top