Is a shorter statement possible in this case?

user1234 user1234 at 12.de
Mon Nov 6 05:14:16 UTC 2023


On Sunday, 5 November 2023 at 18:36:40 UTC, Ctn-Dev wrote:
> I wrote this earlier:
>
> [...]
> 
> if runs when both "One" and "Two" are in the given array as 
> intended, but its conditional statement looks verbose. Is there 
> a more concise way of getting the same result?

Yes, assuming you accept to drop your string arrays then one is 
to use bit flags:

```d
enum NumTraitBits
{
     Empty,
     One     = 0x01,
     Two     = 0x02,
     Three   = 0x04,
     // ...
     _      =  0xF0
}

NumTraitBits numeric_traits_1 = NumTraitBits.Empty;
NumTraitBits numeric_traits_2 = NumTraitBits.Two;
NumTraitBits numeric_traits_3 = NumTraitBits.One;
NumTraitBits numeric_traits_4 = NumTraitBits.Two | 
NumTraitBits.One;

void main() {

     import std.stdio, std.traits;
     void numeric_traits_contains(NumTraitBits numeric) {
         write("contains: ");
         foreach (i; EnumMembers!NumTraitBits)
             if (numeric & i) write(" ", i);
         writeln();
     }

     numeric_traits_contains(numeric_traits_1);
     numeric_traits_contains(numeric_traits_2);
     numeric_traits_contains(numeric_traits_3);
     numeric_traits_contains(numeric_traits_4);
}
```


More information about the Digitalmars-d-learn mailing list