enums and version/static if/"inheritance"

Walter Bright newshound2 at digitalmars.com
Wed Jul 31 19:34:21 UTC 2024


On 7/31/2024 9:04 AM, Max Samukha wrote:
> It's been said maybe a billion times why this solution rarely works in the read 
> world.
I know, it comes up regularly.

A classic case is the antecedent where a list of operating system enum values 
changes with each platform.

I've had the dubious pleasure of having to fix the equivalent for struct fields 
that vary by operating system, and were wrong because it's hard to compare a 
mess of conditional compilation with the operating system spec which does not 
have conditionals in it.

Let's look at the original again:

```
enum FOO {
     A = 5,
     B = 6,
version (x86_64) {
     C = 7,
} else version (AArch64) {
     C = 17,
} else {
     static assert(0);
}
     E = 9, // fixed that!
}
```

The example does follow best practice by adding the static assert for an 
unanticipated operating system. Now, let's add a G for AArch64:

```
enum FOO {
     A = 5,
     B = 6,
version (x86_64) {
     C = 7,
} else version (AArch64) {
     C = 17,
} else {
     static assert(0);
}
     E = 9,
     G = 10,
}
```

Does x86_64 have a G, or not? Is the programmer going to check each supported 
system for G? No, they're not. Are they going to wrap it in its own version 
declaration? Nope. (Even if they do, it runs afoul of what to do about the else 
clause.) I see it again and again. I fix them again and again. Sometimes they 
are never caught at all.

One could put G in the AArch64 block, but then it is out of order, making it 
hard to check them against the operating system spec which will be in order.

But if the operating systems are in separate declarations, this is not an issue. 
The person adding G to x86_64 doesn't need to check operating systems he's not 
familiar with.

Getting the enum values wrong results in really hard to debug failures.

I know you don't find this convincing.


More information about the Digitalmars-d mailing list