By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,156 Members | 989 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,156 IT Pros & Developers. It's quick & easy.

portable code and enums of various sizes

P: n/a
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?

--
Simon Elliott http://www.ctsn.co.uk
Feb 23 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a

Simon Elliott wrote:
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.

Feb 23 '06 #2

P: n/a
On 23/02/2006, Earl Purple wrote:
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.

--
Simon Elliott http://www.ctsn.co.uk
Feb 24 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.