Intelligent enums

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 18 22:56:51 PST 2017


On Thursday, 19 January 2017 at 03:47:34 UTC, Ignacious wrote:
> On Thursday, 19 January 2017 at 02:59:04 UTC, Ignacious wrote:
>> I have the need to create an enum flag like structure to 
>> specify certain properties of a type easily.
>>
>> e.g.,
>>
>> enum properties
>> {
>>    Red,
>>    Blue,
>>    Hot,
>>    Sexy,
>>    Active,
>>    ...
>> }
>>
>> But some properties will be mutually exclusive. I would like 
>> to contain all those rules for in the enum itself for obvious 
>> reasons(encapsulation).
>>
>> I guess I'm going to be told to use static and structs, but 
>> I'm hoping for a more elegant solution.
>
> I should be clear that I'm using these as flags using 
> EumToFlags and I want to prevent certain flags from betting set 
> in certain combinations that are invalid.

If their only use is for Enum to flags (i.e. you don't care at 
all about the enum)
then you can use std.bitmanip.bitfields to logically group the 
combinations.
i.e. have all the mutually exclusive combination in the same 
field.

e.g.

struct properties
{
     enum colour { red, blue }
     // any other mutually exclusive combinations.
     mixin(bitfields!(colour, "colour" , 1
                             bool  , "hot" , 1));
}


More information about the Digitalmars-d-learn mailing list