enum inheritance

JS js.mdnq at gmail.com
Mon Jul 15 01:13:25 PDT 2013


On Monday, 15 July 2013 at 07:37:36 UTC, Mike Parker wrote:
> On Monday, 15 July 2013 at 04:27:42 UTC, JS wrote:
>> BTW, the usefulness is to group sub-enums into the same range. 
>> This would make it easy/efficient to branch over a range in 
>> the enum:
>>
>> if (v in colors.Red) { v is a color in red }
>>
>> instead of
>>
>> if (v is color.Red || v is color.RedOrange || ...)
>
> if( v >= Red && v <= LastRed )

The problem is if a binary is already compiled and changes are 
made. If a red color is inserted your range has changed. Also, it 
requires you to keep your entries sorted properly. Also, a 
"LastRed" entry is needed and there is no other reason to have it.

Since an int is 4B entries, and that's way more than most will 
use, It think it's better to be able to have the compiler 
partition of the range for you and save "space" for future 
entries. This prevents an addition entry from screwing up 
everything.


e.g.,

enum colors
{
     enum Red : 1M { RedOrange, ... }
     enum Green : 2M {  ... }
     ...
}

In this case, one can have up to 1M unordered sub entries(should 
be plenty) and ~4.2k main entries. One could order further,


enum colors
{
     enum Red : 1M { enum RedOrange : 10k { }, ... }
     enum Green : 2M {  ... }
     ...
}

Basically the idea is to distribute the elements of enum and sub 
enums in such a way as to maximize space between each entry. This 
allows any binaries using an old version not to crash and burn. 
This does require an estimation of the maximum entries that will 
be used.

I'm particularly thinking of a messaging system where ints can be 
passed around with 10's of thousands of defined messages with 
messages grouped into common functionality(hence the inheritance 
aspect) and adding new messages won't ruin the communications 
between new and old systems.

Nested switch statements can easily and quickly pare down 
determination of a message(not as fast as a flattened hierarchy 
though).



More information about the Digitalmars-d-learn mailing list