Post #2813115
2026-05-11 13:59 UTC
@thephd@pony.social Out of interest, what's your best recommendation for writing a _Generic that switches on two of its operand types, if the choices aren't independent and there's no default clause?
In my 2023 article I mentioned the idea of using a function type to stand in for a type tuple, via GNU typeof, along the lines of
_Generic((void (*)(__typeof(x), __typeof(y)))NULL,
void (*)(int, int) : "got two ints",
void (*)(int, char *) : "got an int and a string",
void (*)(char *, int) : "got a string and an int")
Now that typeof is standard in C23, that idea doesn't depend on GNU extensions any more. And it's certainly an improvement on the horrible system of integer type ids I suggested as a workaround at the time. But do you have any even better ideas? Ideally, a way to combine it with the N3888 identifiers, so as to be able to get both good features at once – the ability to switch on both types, _and_ the ability to refer to both values inside the branch via correctly typed identifiers?
Replies (1)
-
@thephd@pony.social 2026-05-11 17:21
@simontatham@hachyderm.io I have no good solution for multi match generics other than the function pointer arguments trick. I have sat down to try and figure out a non-amviguous syntax for this but it has not worked out at all. It's similar to the problem of trying to initialize multiple different types in for loop init expressions: very little syntactic space to maneuver. That being said, maybe we need to grow a little beyond Generic if we want this kind of power.